ReSharper
 
Get ReSharper
You are viewing the documentation for an earlier version of ReSharper.

Code Inspection: Assignment to a property of a readonly field can be useless

Last modified: 21 July 2022

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 a 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 does not 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.