Search code examples
c#constructorpropertiesgetter-setter

The 'this' object cannot be used before all of its fields are assigned to


In Constructor Day has problem:

The 'this' object cannot be used before all of its fields are assigned to.

But in the same case for Month in Constructor it works. Why?

struct Date
{
    private byte day;

    public byte Day
    {
        get { return day; }
        set {
            if (value > 0 && value < 32)
                day = value;
            else
                day = 0;
        }
    }

    private byte month;

    public byte Month
    {
        get { return month; }
        set
        {
            if (value > 0 && value < 13)
                month = value;
            else
                month = 0;
        }
    }

    public Date(byte day, byte month)
    {
        Day = day;
        Month = month;
    }
}

Solution

  • It doesn't, the compiler is just stopping after the first error. If you comment out Day = day you'll see the same error on Month = month.

    (Tested with dotnetfiddle/.NET 4.7.2, I suppose other compilers may be different.)