Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does resharper suggests using readonly in fields that are not changed?

Tags:

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

like image 739
gabbi soloer Avatar asked Mar 07 '10 12:03

gabbi soloer


People also ask

What does readonly do in C#?

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.

How do you make a field read only in C#?

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.


2 Answers

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.

like image 193
tvanfosson Avatar answered Oct 14 '22 19:10

tvanfosson


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.

like image 32
P Daddy Avatar answered Oct 14 '22 20:10

P Daddy