Child pages
  • Assignment to a property of a readonly field can be useless
Skip to end of metadata
Go to start of metadata

Consider the following situation — say you have an interface I and a struct that implements this interface:

Now, say you have a class that has a readonly field of a type that implements I and a static method which assigns the readonly variable, like so:

If you now call the method with A<S>.Foo(), you’d expect it to print the value 7 to the console. In actual fact, it prints 0 (zero).

The main reason for this is that readonly fields can only be initialized in the constructor. Since this doesn’t happen, the value of X is essentially the value of default(T). In the case of reference types, this will be null and will throw a NullReferenceException were you to run the code above. However, with value types, this presents a hidden error, as default(T) will yield a default-initialized S structure with its Y property predictably set to 0.

  • No labels