7

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œur
  • 37,241
  • 25
  • 195
  • 267
mgamer
  • 13,580
  • 25
  • 87
  • 145

3 Answers3

11

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.

Community
  • 1
  • 1
Ani
  • 111,048
  • 26
  • 262
  • 307
4

This happens because an int local variable (unlike an int as a class or struct member) has no default value. The struct output in your example only works because it has no members.

Default values discussed here.

This would work:

struct MyStruct
{
    int c;
}

int a = new int();
MyStruct b = new MyStruct();

Console.WriteLine(a);
Console.WriteLine(b);
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
2

The compiler simply doesn't like the fact that your integer is used before being initialized.

Error   5   Use of unassigned local variable 'a'    
Otávio Décio
  • 73,752
  • 17
  • 161
  • 228