Wojtek
Wojtek

Reputation: 145

Initialization of get-only property in owner-object initializer

last time I came across a construct in C# Object Initializer:

having:

public class Class1
{
    public Class2 GetterOnlyProperty { get; private set; }

    public Class1()
    {
        this.GetterOnlyProperty = new Class2();
    }
}

the initialization may be as follow:

var class1 = new Class1()
{
    GetterOnlyProperty =
    {
        Prop1 = Value1,
        Prop2 = Value2,
        …
    }
};

Please note that there is no new keyword after GetterOnlyProperty, the Instance for GetterOnlyProperty must be created in constructor of Class1, otherwise NullReferenceException will be thrown. This instance is taken and properties are initialized.

It works like a charm, but I haven't found documentation of this feature in MSDN. Is this feature documented? Could you provide me with a link to the documentation?

Thanks in advance! Wojtek

Upvotes: 3

Views: 339

Answers (1)

dcastro
dcastro

Reputation: 68650

It's in section §7.6.10.2 Object initializers of the C# Spec.

A member initializer that specifies an object initializer after the equals sign is a nested object initializer, i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.

As for nested collection initializers:

A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the field or property, the elements given in the initializer are added to the collection referenced by the field or property. The field or property must be of a collection type that satisfies the requirements specified in §7.6.10.3

Upvotes: 3

Related Questions