Is there such a thing as a chained NULL check?

前端 未结 7 439
灰色年华
灰色年华 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:07

    .NET Fiddle

    As stated there is a plan to have c# 6.0 implement the ? operator to facilitate this process somewhat. If you cannot wait, I would suggest using a lambda expression and a simple helper function to solve this.

    public E NestedProperty(T Parent, Func Path, E IfNullOrEmpty = default(E))
    {
        try
        {
            return Path(Parent);
        }
        catch
        {
            return IfNullOrEmpty;
        }
    }
    

    This could be used int value = NestedProperty(blank,f => f.Second.Third.id); as shown in the demo below

    program

    public class Program
    {
        public void Main()
        {
            First blank = new First();
            First populated = new First(true);
    
            //where a value exists
            int value = NestedProperty(blank,f => f.Second.Third.id);
            Console.WriteLine(value);//0
    
            //where no value exists
            value = NestedProperty(populated,f => f.Second.Third.id);
            Console.WriteLine(value);//1
    
            //where no value exists and a default was used
            value = NestedProperty(blank,f => f.Second.Third.id,-1);
            Console.WriteLine(value);//-1
        }
    
        public E NestedProperty(T Parent, Func Path, E IfNullOrEmpty = default(E))
        {
            try
            {
                return Path(Parent);
            }
            catch
            {
                return IfNullOrEmpty;
            }
        }
    }
    

    simple demo structure

    public class First
    {
        public Second Second { get; set; }
        public int id { get; set; }
        public First(){}
        public First(bool init)
        {
            this.id = 1;
            this.Second = new Second();
        }
    }
    
    public class Second
    {
        public Third Third { get; set; }
        public int id { get; set; }
        public Second()
        {
            this.id = 1;
            this.Third = new Third();
        }
    }
    
    public class Third
    {
        public int id { get; set; }
        public Third()
        {
            this.id = 1;
        }
    }
    

提交回复
热议问题