Differences between user-created structures and structure structures in .NET.

Why does the C # compiler not allow you to compile this:

int a; Console.WriteLine(a); 

but allows you to compile:

 MyStruct a; Console.WriteLine(a); 

where MyStruct is defined as:

 struct MyStruct { } 

Update: in the first case, the error:

Error 1 Using unassigned local variable 'a'

+7
c # struct value-type
source share
3 answers

C # does not allow reading from uninitialized locales. Here is an excerpt from the language specification that applies in this context:

5.3 Specific purpose

...

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


Clearly, since your structure has no fields, this is not a problem; he is considered definitely designated. Adding a field to it should break the assembly.

Regarding some note:

11.3.8 Constructors

The member instance function cannot be called until all fields of the constructed structure are definitely assigned.

+11
source share

This is because the local int variable (unlike int as a member of a class or structure) does not have a default value. The struct output in your example only works because it has no members.

The default values ​​are discussed here .

This will work:

 struct MyStruct { int c; } int a = new int(); MyStruct b = new MyStruct(); Console.WriteLine(a); Console.WriteLine(b); 
+4
source share

The compiler just doesn't like the fact that your integer is used before initialization.

 Error 5 Use of unassigned local variable 'a' 
+2
source share

All Articles