简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM