C# null check chain in method call

前端 未结 4 590
心在旅途
心在旅途 2021-01-20 15:03

I suppose method call chain below.

void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
            


        
4条回答
  •  执笔经年
    2021-01-20 15:24

    You can do

    void DoSomething()
    {
        CreateA()?.Foo();
    }
    
    ObjectA CreateA()
    {
        return CreateB()?.ToA();
    }
    

    Your other approach if you can't use C# 6, is don't return nulls, use null objects that way you never have to deal with null checking ( but you can still check if something is the null object )

提交回复
热议问题