Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no "Use of unassigned local variable" compile error on an empty user defined struct?

Tags:

c#

The following compiles successfully:

struct Foo {}

void Test()
{
    Foo foo;
    foo.ToString();
}

Whereas the following yields a "Use of unassigned local variable" compile error.

struct Foo
{
    int i;
}

void Test()
{
    Foo foo;
    foo.ToString();
}

It appears that in the first case, the compiler has made some sort of inference that since the struct has no members, they do not need to be initialized. But I'm not sure that this makes sense to me. The compiler could have forced you to initialize the foo variable as new Foo().

So, if in C# all local variables must be initialized before accessing, why does the first example compile?

like image 781
Zaid Masud Avatar asked Sep 21 '12 12:09

Zaid Masud


1 Answers

Section 5.3 of the C# 5 specification covers this:

A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.

That's automatically the case when there are no instance variables, hence the variable is considered to be definitely assigned, and can be used in the ToString() call.

like image 89
Jon Skeet Avatar answered Oct 14 '22 19:10

Jon Skeet