A primitive C# value type, for example int
is a struct. So, why is int
not initialized? There supposed to be default constructor, I think. On the other hand, a custom struct is ok.
In the following code
struct STRCT { }
class Program
{
static void Main(string[] args)
{
STRCT strct;
strct.Equals(8);
strct.GetHashCode();
strct.GetType();
strct.ToString();
int i;
i.Equals(8);
i.GetHashCode();
i.GetType();
i.ToString();
}
}
while first 5 lines of code are ok from the C# compiler view, next 5 lines of code generates compile error:
use of unassigned local variable
Please, explain why? From my point of view both types are structs and shall have the same behavior.
It's a pathological extreme of the rules of Definite Assignment. Specifically:
A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.
In this case (STRCT strct
), the set of instance variables is empty, and so it is true that they've all been definitely assigned.
This is because, unlike the int
, your STRCT
doesn't contain any fields and therefore doesn't contain anything that could be "unassigned".
Try changing it to:
struct STRCT
{
public int X;
}
Then you'll get the same compile error:
Error CS0165 Use of unassigned local variable 'strct' ConsoleApplication1 D:\Test\CS6\ConsoleApplication1\Program.cs 15
The C# language specification has explicit rules for "Definite Assignment" in section 5.3:
At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by a particular static flow analysis (§5.3.3), that the variable has been automatically initialized or has been the target of at least one assignment
And then:
A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.
So from that last rule, if a struct has no instance variables (i.e. fields) then it is considered to be "definitely assigned", and therefore no compile error will be omitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With