views:

754

answers:

3

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?

A: 

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;
    }
}
Vadim
A: 

Because, unlike the classes, which are stored in the heap, The structs are value objects, and will be saved in the stack. It's the same principle of assigning a local variable before using it.

Jhonny D. Cano -Leftware-
+3  A: 

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.

Lasse V. Karlsen