Why do I need to assign all fields inside a constructor constructor?

Duplicate:

Why should I initialize all fields in my C # structure using an unnamed constructor?


If in the constructor of such a structure as

internal struct BimonthlyPair { internal int year; internal int month; internal int count; internal BimonthlyPair(int year, int month) { this.year = year; this.month = month; } } 

I do not initialize the field (account in this case) I get an error message:

The 'count' field must be fully assigned before control is returned to the subscriber

But if I assign all the fields, including count in this case, with something like

 this.year = year; this.month = month; this.count = 0; 

the error has disappeared.

I think this is because C # does not initialize the structure fields when someone creates a new structure object. But why? As far as I know, it initializes the variables in some other contexts, so why are the structure different decorations?

+4
source share
3 answers

When you use the default constructor, there is an implicit guarantee that the entire structure value will be cleared.

When you create your own constructor, you inherit this guarantee, but don't get the code that uses it, so you need to make sure that the whole structure matters.

+8
source

I can not answer why. But you can fix it with: this ().

 internal struct BimonthlyPair { internal int year; internal int month; internal int count; internal BimonthlyPair(int year, int month) : this() // Add this() { this.year = year; this.month = month; } } 
+6
source

Because, unlike classes that are stored on the heap, structures are value objects and will be stored on the stack. This is the same principle of assigning a local variable before using it.

0
source

All Articles