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
}