Why does resharper suggests using readonly in fields that are not changed
to clearify the question, I'd like to add that I'm not asking why I should choose readonly over const or what are the benefits of readonly over const.
I'm asking why to make a field readonly just because it's not changed (at the moment).
Thanks
Please sign in to leave a comment.
One reason would be for example readability. If you're expliciting declaring that the field is readonly and only assign it in the constructor, then someone looking at your code understands that the value does not change onces it's been assigned. This is very typical when doing things such as Dependeny Injection.
--
Hadi Hariri
Technology Evangelist
JetBrains, Inc
"Develop with pleasure!"
http://www.jetbrains.com | http://hadihariri.com | http://twitter.com/hhariri
Are there any other reasons ?
because one could argue that a readonly indication where it's not logically correct could be misleading to other programmers in the future..
But then why would you place it somewhere that is not logical? I'm not sure I follow. Readonly is an indication that the value will not be modified after being initialized. If it's going to be modified then it doesn't make sense for it to be readonly. In the future, sure, then you remove it. But otherwise it's YAGNI (You aren't going to need it).
It is also worth noting that a "readonly indication where it's not logically correct" produces a compilation error, so you need not worry about missing a potential point of confusion for a future programmer.
Hello!
How this resharper rule correlates with Microsoft security warnings?
https://msdn.microsoft.com/en-us/library/ms182296.aspx
CA2104: Do not declare read only mutable reference types
and
CA2105: Array fields should not be read only
I think Microsoft is being a bit too prescriptive here. The point of these rules is so that you don't confuse a readonly field with a field that has readonly values. This is very valid advice, but these rules are telling you to ignore readonly completely in order to not make this mistake, which I think is too broad. It's also perfectly valid to declare a field as readonly but have mutable values, e.g. to prevent excessive memory traffic, you update an array in place, rather than re-allocate it all the time. So, really, it's up to you. If you're happy that you know why you're making a field readonly, stick with ReSharper's suggestions. If you'd rather follow Microsoft's cautious approach, change the severity of ReSharper's suggestions so they're displayed as a hint, or not shown at all (alt+enter on a suggestion and change the inspection options).
Hello,
Whoa, it's the good old "don't mix char const* with char *const" thing :)
—
Serge Baltic
JetBrains, Inc — http://www.jetbrains.com
“Develop with pleasure!”