views:

150

answers:

2

I've noticed Resharper suggestion under "Common Practices and Code Improvements": Convert local variable or field to constant.

I've also noticed that in Bill Wagner's book "Effective C#: 50 Specific Ways to Improve Your C#" there is a langauge idiom "Prefer readonly to const" in which author explain risks of using consts.

My question is not about differences between readonly and const and when to use them, but why the one source put const as a common practice/code improvement and in the other hand the second one treats readonly as an idiom?

+1  A: 

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.

dcp
It asks me even on initializing readonly field.
ventr1s
Yes, if the readonly field is declared as an instance variable and you don't change it's value anywhere in the code, you'll get that warning. And I tend to agree with Resharper here instead of Bill Wagoner, for the reasons I mentioned in my edit. But Wagoner makes good points, it's just a matter of opinion.
dcp
+3  A: 

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.

Nicole Calinoiu
This is the key point here. There is no maintainability concern with private constants, as they can never be directly baked into external assemblies.
Dan Bryant