Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between user created structs and framework structs in .NET

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'

like image 460
mgamer Avatar asked Nov 24 '10 15:11

mgamer


1 Answers

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.

like image 90
Ani Avatar answered Sep 24 '22 05:09

Ani