Search code examples
c#visual-studio-2010propertiesinitializationnested-properties

c# Initializing Inner properties


I have two classes:

public class TmpClass
{
    public TmpClass() 
    {
        InnerClass = new InnerClass();
    }

    public InnerClass InnerC { get; set; }
}

public class InnerClass
{
    public string Name { get; set; }
}

And is it possible to initialize property of InnerClass like this, becouse in this way VS2010 cannot does it.

TmpClass a = new TmpClass()
{
    InnerC.Name = "blabla"
}

Solution

  • Use next code snippet:

    TmpClass a = new TmpClass
    {
        InnerC = new InnerClass { Name = "Name" }
    };
    

    Note, that statement new TmpClass will call a constructor by default. Also note: you have wrong constructor declaration. Change TmpClass constructor to next code sample, so that it will compile:

    public TmpClass() 
    {
        InnerC = new InnerClass();
    }