Saturday, October 18, 2014

Why use readonly (versus const)

I was playing around with Resharper today and ran a code analysis on one of my projects which came back with 430 code issues. One of the suggestions said there were fields I should mark as 'readonly'. And this then reminded me of this question I've sometimes been wondering.

Today I finally Googled it and it resulted in a "Oh yeah..." moment. The top answer in StackOverflow being:
The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. 
 I've run into this problem many times before where I try to assign DateTime (for something like Today) or a List (of required names) into constant variable. Up until now my solution was just remove the 'const' modifier.

Also readonly allows the class to assign it during the constructor so if for example you need one instance, which should never be reassigned after initialization, but need to also do some set up work, readonly would be a good use for that... if the object is used within the class only.

If the object is also public though, you make want to consider using a getter instead like in the singleton pattern.

I usually use readonly on ViewModels as when a window is initialized, these are created but should never be replaced afterwards. It's probably a no-brainer but just for some added insurance, you can use the readonly modifier on it.

And Resharper made my Visual Studio really slow... so bye bye Resharper!

No comments:

Post a Comment