Automatically implemented property in struct can not be assigned

Vasya picture Vasya · Oct 6, 2011 · Viewed 13.8k times · Source

I have a next code:

struct T 
{
    public T(int u) 
    { 
        this.U = 10; //Errors are here
    }

    public int U { get; private set;  }
}

C# compiler give me a pair of errors in stated line: 1) Backing field for automatically implemented property 'TestConsoleApp.Program.T.U' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. 2) The 'this' object cannot be used before all of its fields are assigned to

What I do wrong? Help me understand.

Answer

Enigmativity picture Enigmativity · Oct 6, 2011

From the C# Specification:

10.7.3 Automatically implemented properties

When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field.

[Deleted]

Because the backing field is inaccessible, it can be read and written only through the property accessors, even within the containing type.

[Deleted]

This restriction also means that definite assignment of struct types with auto-implemented properties can only be achieved using the standard constructor of the struct, since assigning to the property itself requires the struct to be definitely assigned. This means that user-defined constructors must call the default constructor.

So you need this:

struct T 
{
    public T(int u)
        : this()
    { 
        this.U = u;
    }

    public int U { get; private set; }
}