Why is there no "Use unrecognized local variable" error with an empty user structure?

The following compilations succeed:

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

While the following leads to a compilation error "Using an unassigned local variable".

 struct Foo { int i; } void Test() { Foo foo; foo.ToString(); } 

It seems that in the first case, the compiler made some conclusion that since the structure has no members, they do not need to be initialized. But I'm not sure if this makes sense to me. The compiler could force you to initialize the variable foo as new Foo() .

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

+7
source share
1 answer

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.

This is automatic when there are no instance variables, so the variable is considered definitely assigned and can be used in a ToString() call.

+6
source

All Articles