Is there such a thing as a chained NULL check?

前端 未结 7 447
灰色年华
灰色年华 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条回答
  •  有刺的猬
    2021-01-18 06:28

    Since 3.5 (maybe earlier), You could write very simple extension method

      public static TResult DefaultOrValue (this T source, 
                                                    Func property) where T : class
        {
            return source == null ? default(TResult) : property(source);
        }
    

    You may name this method even shortier and then use like this

     var instance = new First {SecondInstance = new Second 
                              {ThirdInstance = new Third {Value = 5}}};
            var val =
                instance .DefaultOrValue(x => x.SecondInstance)
                    .DefaultOrValue(x => x.ThirdInstance)
                    .DefaultOrValue(x => x.Value);
            Console.WriteLine(val);
            Console.ReadLine();
    

    so source classes are:

    public class Third
    {
        public int Value;
    }
    
    public class First
    {
        public Second SecondInstance;
    }
    
    public class Second
    {
        public Third ThirdInstance;
    }
    

提交回复
热议问题