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