I have two similar structs in C#, each one holds an integer, but the latter has get/set accessors implemented.
Why do I have to initialize the Y
struct with
The reason one is valid while the other is not is that you cannot call methods on uninitialised objects. Property setters are methods too.
public struct X
{
public int a;
public void setA(int value)
{ this.a = value; }
}
public struct Y
{
public int a { get; set; }
}
class Program
{
static void Main(string[] args)
{
X x;
x.setA(1); // A: error
x.a = 2; // B: okay
Y y;
y.a = 3; // C: equivalent to A
}
}
The reason that is not allowed is that the property setter could observe the uninitialised state of the object. The caller does not know whether the property setter merely sets a field, or does more than that.