Code Inspection: Assignment to a property of a readonly field can be useless
Consider the following situation - say you have an interface I
and a struct that implements this interface:
interface I
{
int Y { get; set; }
}
struct S : I
{
public int Y { get; set; }
}
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:
class A<T> where T : I
{
readonly T X;
public static void Foo()
{
var a = new A<T>();
a.X.Y = 7; // here
Console.WriteLine(a.X.Y);
}
}
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
.