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?
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:
Some details:
The only difference between normal field and read-only field is flag
initonlyin 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.