There's a tremendous amount of confusion in this thread.
The principle is this: until all of the fields of an instance of a struct
are definitely assigned, you can not invoke any properties or methods on the instance.
This is why your first block of code will not compile. You are accessing a property without definitely assigning all of the fields.
The second block of code compiles because it's okay to access a field without all of the fields being definitely assigned.
One way to definitely assign a struct
is to say
EmpStruct empStruct = new EmpStruct();
This invokes the default parameterless constructor for EmpStruct
which will definitely assign all of the fields.
The relevant section of the specification is §5.3 on Definite Assignment. And from the example in §11.3.8
No instance member function (including the set accessors for the properties X
and Y
) can be called until all fields of the struct being constructed have been definitely assigned.
It would be more helpful (ahem, Eric Lippert!) if the compiler error message were along the lines of
Use of not definitely assigned local variable empStruct
.
Then it becomes clear what to search for the in the specification or on Google.
Now, note that you've defined a mutable struct. This is dangerous, and evil. You shouldn't do it. Instead, add a public constructor that lets you definitely assign firstNumber
and secondNumber
, and remove the public setter from EmpStruct.FirstNumber
.