Chris Arnold
Chris Arnold

Reputation: 5753

Compiler-Implemented Immutability in .Net

Given this class...

public class Test
{
  private long _id;

  public Test(long id)
  {
    _id = id;
  }
}

Will the .Net compiler actually compile it as...

public class Test
{
  private readonly long _id;

  public Test(long id)
  {
    _id = id;
  }
}

In other words, does it understand that _id is only ever set from the constructor and is, therefore, readonly?

Upvotes: 2

Views: 103

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

The compiler cannot possibly know that a field is set only in the constructor. Imagine for example using reflection in some method where the name of the field is read from a database. You need to explicitly specify the readonly keyword if you want the field to be immutable.

Upvotes: 2

Fredrik Mörk
Fredrik Mörk

Reputation: 158389

No, the compiler does not do that. The IL code for the field will be like this:

.field private int64 _id

...while a readonly version would get this IL code:

.field private initonly int64 _id

Upvotes: 4

Related Questions