5

I am trying out Resharper and i notice that it is recommending to set instance level fields to readonly. For example:

private readonly IConnection _connection;

public RetrieveCommand(IConnection connection) {
    _connection = connection;
}

What is the benefit of marking fields like this readonly?

Josh
  • 1,001
  • 9
  • 18

2 Answers2

8

What are the benefits to marking a field as readonly in C#?

Community
  • 1
  • 1
aku
  • 122,288
  • 32
  • 173
  • 203
5

It recommends that you should set it to readonly because the only place you assign the _connection member is in the constructor. That is the only place you are allowed to assign to a readonly member.

See this article for an explanation: Developer Corner: Mark C# class data member as readonly when it's read only

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Colin
  • 10,630
  • 28
  • 36