views:

50

answers:

2

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?

+2  A: 

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
Fredrik Mörk
+2  A: 

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.

Darin Dimitrov
This is slightly misleading and doesn't really answer the question. Consider the "opposite" situation where you have a `private readonly` field: The compiler *does* know if you try to set that field from anywhere except the declaration/constructor, but there's also nothing to stop you setting it from elsewhere using reflection. If the compiler can validate usage of `private readonly` fields then there's no (theoretical) reason why it couldn't verify usage of non-`readonly` fields too.
LukeH