to clarify 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).
for example: if I'd write the following class:
public class MyClass { public int _i = 5; // Code that doesn't change the value of i: ... }
Resharper will indicate that it can be made readonly.
Thanks
Use the readonly keyword in C# The readonly keyword can be used to define a variable or an object as readable only. This means that the variable or object can be assigned a value at the class scope or in a constructor only.
If we use readonly keyword with fields, those field values will evaluate at the runtime. To define read-only fields in c#, we need to use readonly keyword during the declaration of fields in our application, and we can use readonly modifier with the numbers, boolean values, strings, or null references.
When it detects that you are not assigning to a variable except at initilization, it presumes that you don't want the variable to change. Making the variable readonly (or const) will prevent you from assigning to the variable in the future. Since this seems (by usage) to be the behavior you want, it makes the suggestion that you formalize it and derive the benefit of the protection.
I usually try to remember1 to do what Resharper's trying to remind you to do. If I have any fields that are immutable, I like to mark them with readonly
to formalize that. On many types, I do this will all the fields. There are benefits of immutability ([2] [3]), and Resharper is trying to help you take advantage of them.
1 I personally don't use Resharper. I have my reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With