Misconception around `readonly` of C#

Shiljo Paulson
2 min readFeb 3, 2022
Photo by Belinda Fewings on Unsplash

as per dictionary

capable of being viewed but not of being changed or deleted

here in this blog post will explain about the ‘readonly’ & I have noticed that there is a misconception surrounding the ‘readonly’.

Characteristic of `readonly`

  • Can be initialized while declaring it like the example below.
  • Can be initialized while in the constructor like the below example.
  • Cannot be initialized/assigned after the execution of `constructor` like the below example even if we try then will get compiler error since it is assigned outside constructor here in this case it’s from Execute method.

Misconception

Some developers have misconceptions that marking the variable as ‘readonly’ will make it as read only & cannot be modified.

here in the above example at line number 15

_departmentMappings.Add(id, departmentName);

some say we will get error, or it won’t allow you to add items to the dictionary, but truth is it allows you to add items to it.

The keyword readonly basically prevents the field from being replaced/reinitialized by/with a different instance...

In case if someone wants to stop items being added to Dictionary there are special Collections for it & it's called ReadOnlyDictionary (it is available since .Net Framework 4.5) & there is another one ReadOnlyCollection (which is available since .Net Framework 2.0) as the name implies ReadOnlyDictionary is for dictionaries and ReadOnlyCollection is for List.

In ReadOnlyDictionary you might not find Add, Remove, Clear & etc... methods won’t work to know more about ReadOnlyDictionary have a look at source code of it.

Let me know your valuable comments.

--

--

Shiljo Paulson

Full stack Developer, good at OOPs, .Net, C#, TypeScript, JavaScript, SQL, HTML. Recent times interest is on Cloud, System Design and GoLang.