Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ReSharper prefer consts over readonly?

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 language idiom "Prefer readonly to const" in which the author explains the risks of using consts.

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

like image 937
Dariusz Woźniak Avatar asked Aug 03 '10 16:08

Dariusz Woźniak


2 Answers

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.

like image 62
Nicole Calinoiu Avatar answered Oct 22 '22 17:10

Nicole Calinoiu


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.

like image 26
dcp Avatar answered Oct 22 '22 16:10

dcp