I was looking through my codebase and found a line of code that R# had helpfully refactored for me. Here's a representative sample:
public class A
{
public B Target { get; private set; }
public object E { get; set; }
public A()
{
Target = new B();
}
}
public class B
{
public object C { get; set; }
public object D { get; set; }
}
public static class Test
{
static A LocalA;
static void Initialize()
{
LocalA = new A
{
E = "obviously this should be settable",
Target =
{
C = "Whoah, I can set children properties",
D = "without actually new-ing up the child object?!"
}
};
}
}
Essentially, initialization syntax allows for setting a child object's public properties without actually performing the constructor call (obviously if I pull the Target
constructor call from the constructor of A
, the whole initialization fails due to a null reference.
I've searched for this, but it's difficult to put into Google-able terms. So, my question is: (a) what is this called exactly, and (b) where can I find some more information in C# documentation about it?
Edit
Looks like someone else has asked this with similar lack of documentation found: Nested object initializer syntax