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?
Section 5.3 of the C# 5 specification covers this:
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.