Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit to making a C# field read-only if its appropriate?

Tags:

I am working on a project using ReSharper. On occasion it prompts me that a field can be made readonly. Is there any performance or other benefit to this? I am presuming the benefits would be quite low-level, or would any benefits be purely semantic?

Thanks

With example below the field was initially just private, but resharper prompted to set it as readonly. I understand the reason why it can be set as readonly, ie. its being set in the constructor and not changed again, but just wondering if there are any benefits to this...

public class MarketsController : Controller {     private readonly IMarketsRepository marketsRepository;      public AnalysisController(IMarketsRepository marketsRepository)     {                         this.marketsRepository = marketsRepository;     } } 

Edit What is the easiest way to look at the MSIL?

like image 985
Matt Avatar asked Aug 03 '10 10:08

Matt


People also ask

Is it worth getting air conditioning?

Air conditioners help circulate and filter the air. These systems also help remove pollutants from the air you breathe. This is vital especially for individuals who suffer from conditions such as allergies and asthma. Air conditioning helps reduce the irritants that cause these health problems.

Is AC good for human body?

Cooling is obviously one of the greatest health benefits of air conditioning. But it does more than just keep you comfortable in the summer. AC can make conditions better for preventing heat related symptoms or for recovering from illness.


2 Answers

The benefit is purely semantic. It will help users of your code explicitly understand that this field can't be changed after object is created. Compiler will prevent unwanted changes of this field. I totally agree with following quote from Python Zen:

Explicit is better than implicit.

Some details:

The only difference between normal field and read-only field is flag initonly in IL. There is no optimization about it (as with constants) because actually it allows all operations (get and set, but only in ctor). It is just hint to compiler: don't let it be changed after construction.

.field public initonly int32 R 
like image 135
Andrey Avatar answered Sep 20 '22 14:09

Andrey


It's not so much low-level performance, but more high-level maintainability. Making things readonly is one of the possibilities you have to limit and control the number of places a certain value can be changed. This in turn means that you reduce interdependency between classes (a.k.a. "loose coupling"); the result is an application that has fewer internal dependencies and thus a lower complexity. In other words, readonly fields and properties make your application more maintainable.

like image 44
tdammers Avatar answered Sep 20 '22 14:09

tdammers