Why C# compiler does not allow you to compile this:
int a;
Console.WriteLine(a);
but does allow you to compile:
MyStruct a;
Console.WriteLine(a);
where MyStruct is defined as:
struct MyStruct
{
}
Update: in the firsts case the error is:
Error 1 Use of unassigned local variable 'a'
C# does not allow reading from uninitialized locals. Here's an extract from language specification that applies in this context:
5.3 Definite assignment
...
A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.
Clearly, since your struct has no fields, this isn't an issue; it is considered definitely assigned. Adding a field to it should break the build.
On a somewhat related note:
11.3.8 Constructors
No instance member function can be called until all fields of the struct being constructed have been definitely assigned.
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