Search code examples
.netimmutabilityreadonly

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?


Solution

  • 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