I recently posted a question about the use of readonly on stackoverflow. Follow the link to see the comments on Thoughts on the use of readonly for any/all instance members of a class?
For some time now I’ve been using the readonly modifier for nearly all class fields. I use it for List
I personally find the following benefits to marking all (nearly enough) fields as readonly:
- You do not have to check to see if the field is null outside of initialization
- By reviewing the field definition you can tell if the value is going to change
- Prevents accidental ‘side-effects’ of various methods on an object
- Greater ability to use objects across threads
I confess that my habitual use of readonly stems from my passion about immutable objects in general. Though C# is not the greatest language in the world for supporting immutability; it still is a worth-while effort. Immutability of an object allows sharing across threads, predictable behavior, cache or reuse of objects, and other benefits. The other thing I like about it is that it’s damn hard to write a setter on an immutable object (death to the setters).
As another note related to readonly I would recommend ‘static readonly’ over ‘const’ declaration every time. The compiler treats ‘const’ definitions as C++ does a ‘#define’ and translates the use into the actual value at compilation time. Using the ‘static readonly’ approach allows you to change a constant in one assembly and it take affect in another without requiring you to recompile it.