user2567674 user2567674 - 3 years ago 145
C# Question

C# check null on an object and its property

I'd like to tidy up this piece of code, any idea?


  • 1 object is not null

  • 1 of its property is not null either

    var v = Values.Find(x => x.id.Equals(Properties.Resources.myString));
    if (v != null && v.Property != null)
    {
    // do something with 'v.Property'
    }


Answer Source

C# 6.0 will probably best serve you here with the null conditional operator:

var v = Values.Find(x => x.id.Equals(Properties.Resources.myString));
var result = v?.Property?.DoSomething();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download