C# null check chain in method call

前端 未结 4 594
心在旅途
心在旅途 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:27

    Starting with C# 6.0 you can use Null-Conditional Operator, which lets you make null-checking implicitly:

    var result = possiblyNull?.MethodThatCanReturnNull()?.SomeProperty;
    

    This construct will produce a null result if any element in the chain produces null.

提交回复
热议问题