Why does Resharper prefer consts over readonly?
Private constants do not carry the same risks as public constants. ReSharper is presumably suggesting performance optimizations for cases where a field is not externally visible.
In my experience with ReSharper, you'll get this suggestion if you are setting a variable value in the declaration, but the variable's value never changes throughout the method. In that case, it can be made into a local constant. You'll also get the warning on an instance variable that you initialize in-place, but never change the value anywhere in the class body.
And the author of that book basically makes the argument that by using readonly
instead of const
, you can avoid having to rebuild dependent assemblies if you change the value of the readonly
value. In contrast, for a change to a const
, you'd have to recompile the dependent assemblies against the new version of the assembly with the const
.
It's a legitimate argument, however, if a value is not going to change throughout the life of the application, I still think it's better to use const
. I like to use readonly
for values I'm loading from a configuration, for example, that won't change after being initialized in the constructor.
I think it's much better to have the code clarity that const
provides at the possible expense of a little more compilation maintenance.