Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?
If in the constructor of an struct like
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 don't initialize a field (count in this case) I get an error:
Field 'count' must be fully assigned before control is returned to the caller
But if I assign all fields, including count in this case, with something like
this.year = year;
this.month = month;
this.count = 0;
the error disappeared.
I think this happens because C# doesn't initialize struct fields when somebody creates a new struct object. But, why? As far as I know, it initialize variables in some other contexts, so why an struct is a different scenery?
When you use the default constructor, there is an implicit guarantee that the entire value of the struct is cleared out.
When you create your own constructor, you inherit that guarantee, but no code that enforces it, so it's up to you to make sure that the entire struct has a value.
I cannot answer why. But you can fix it by the use of : 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With