Is there such a thing as a chained NULL check?

前端 未结 7 506
灰色年华
灰色年华 2021-01-18 05:30

I have the following ugly code:

if (msg == null || 
    msg.Content == null || 
    msg.Content.AccountMarketMessage == null || 
    msg.Content.AccountMarke         


        
7条回答
  •  旧时难觅i
    2021-01-18 06:24

    You need monads and Monadic null checking. Could have a look at Monads.Net package. It can help with simplifying null tests and getting values from deep navigation properties

    Something like

    var sObject = person.With(p=>p.Content).With(w=>w.AccountMarketMessage ).With(p=>p.Account).With(p=>p.Object);
    

    If you wanted a default value then

    var sObject = person.With(p=>p.Content).With(w=>w.AccountMarketMessage).With(p=>p.Account).Return(p=>p.Object, "default value");
    

提交回复
热议问题