简体   繁体   中英

instantiate object property on get in one line

This is a question out of curious more so than actual need, but I thought it would be interesting to find out, since I have classes soo deep I need 10 lines of instantiation just to set a single property.

The property [MyObj3] functionally works as I want it to, where on the get property function it checks if the object is null and instantiates it. Whereas [MyObj2] will throw a null reference exception when trying to reference its properties.

But to make every single property in this way is a bit of a bigger nightmare than I want to tackle. So the question here is if there is a simple inline way to handle this. Or any other ways I may not be thinking of.

-- UPDATE: I forgot to mention, I wanted to keep the object null until it is needed, otherwise it gets included in xml serialization.

public class Obj1
{
    public Obj2 MyObj2 { get; set; }

    private Obj3 _obj3;
    public Obj3 MyObj3
    {
        get => _obj3 == null ? _obj3 = new Obj3() : _obj3;
        set => _obj3 = value;
    }
}

public class Obj2
{
    public string MyProp1 { get; set; }
}

public class Obj3
{
    public string MyProp1 { get; set; }
}

public void test()
{
    var obj = new Obj1();
    obj.MyObj2.MyProp1 = "test";//null exception
    obj.MyObj3.MyProp1 = "test";//works fine
}

You could instantiate Obj2 and Obj3 when you instantiate Obj1 like this

public class Obj1
{
    public Obj2 MyObj2 { get; set; } = new Obj2();
    public Obj3 MyObj3 { get; set; } = new Obj3();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM