Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to assign all fields inside an struct's constructor? [duplicate]

Duplicate:

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?

like image 279
eKek0 Avatar asked Dec 07 '22 07:12

eKek0


2 Answers

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.

like image 109
Lasse V. Karlsen Avatar answered Dec 29 '22 01:12

Lasse V. Karlsen


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;
    }
}
like image 30
Vadim Avatar answered Dec 29 '22 00:12

Vadim