I have one observation about struct. When I declare a property in Struct and if I don’t initialize the Struct then it gives me the below error – “Use of unassigned local variable empStruct”
PSeduo Code-
struct EmpStruct
{
private int firstNumber;
public int FirstNumber
{
get { return firstNumber; }
set { firstNumber = value; }
}
public int SecondNumber;
}
Program.cs-
EmpStruct empStruct;
empStruct.FirstNumber = 5;
But when I declare public variable then the above code works.
EmpStruct empStruct;
empStruct.SecondNumber;
So my question is why compiler not gives error when i try to access variable.(In case of Class it will give the error).
There’s a tremendous amount of confusion in this thread.
The principle is this: until all of the fields of an instance of a
structare 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
structis to sayThis invokes the default parameterless constructor for
EmpStructwhich 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
It would be more helpful (ahem, Eric Lippert!) if the compiler error message were along the lines of
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
firstNumberandsecondNumber, and remove the public setter fromEmpStruct.FirstNumber.