Shorthand for nested null checking C#

后端 未结 5 1688
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 09:38

As far as I know there is not a significantly more elegant way to write the following....

string src;
if((ParentContent!= null)
    &&am         


        
5条回答
  •  无人及你
    2020-12-17 10:12

    Correct me, if I am wrong, but this could be solved using C# 6.0's null-conditional operator:

    string src = ParentContent?.Image("thumbnail")?.Property("src")?.Value;
    

    If src is already in used before this value assignment, you could use it as follows:

    string src = ....;
    
    // ...
    
    src = ParentContent?.Image("thumbnail")?.Property("src")?.Value ?? src;
    
    // ...
    

提交回复
热议问题