3

Possible Duplicate:
Shortcut for “null if object is null, or object.member if object is not null”

I wish there were a way to make this type of test simpler in C#:

if (foo != null &&
    foo.bar != null &&
    foo.bar.baz != null &&
    foo.bar.baz.bat != null)
{
    var bat = foo.bar.baz.bat;
    bat.cat = 5;
    bat.dog = 6;
}

One possible feature that would support this is if statements that supported new variable declarations, e.g.

if (foo != null &&
    (var bar = foo.bar) != null &&
    (var baz = bar.baz) != null &&
    (var bat = baz.bat) != null)
{
    bat.cat = 5;
    bat.dog = 6;
}

The gains may not be obvious here, since the proposed solution is actually longer in this example. But with longer names it would really pay off.

Is there any better way to do this? Any chance of a suggestion like this actually making it into a future version of the language (calling Eric Lippert, come in)?

Community
  • 1
  • 1
bright
  • 4,460
  • 1
  • 31
  • 55
  • 2
    It might be a good time to revisit your design where you're having to go four levels deep via the dot operator like that. That's a lot of levels of indirection to have to go through all at once. – Daniel DiPaolo Jun 21 '11 at 21:58
  • 1
    What is your question? StackOverflow is not a .NET features wish list. Use the http://connect.microsoft.com site to request features directly to Microsoft. – Darin Dimitrov Jun 21 '11 at 21:58
  • Well, you could wrap it in a try and catch the NullReferenceException, but I suspect that would be much slower than running the null checks manually. – Martin Törnwall Jun 21 '11 at 21:58
  • Wouldn't writing all those `var bar = ...` be using more space to copy those objects, then check if null. Seems less efficient than the first way. I'm not really sold that the second looks any better either. – Prescott Jun 21 '11 at 21:59
  • 1
    @Prescott - there wouldn't be any copying, unless the nested objects were value types. In that case the proposed solution might actually be more efficient, not less, although that probably depends on the compiler. – bright Jun 21 '11 at 22:15

3 Answers3

2

I usually just move the expression in the if-statement to its own method at the bottom of the file:

if (CheckBat(foo))
{
    var bat = foo.bar.baz.bat;
    bat.cat = 5;
    bat.dog = 6;
}

... snip ...

private bool CheckBat(MyFoo foo)
{
    return foo != null &&
           foo.bar != null &&
           foo.bar.baz != null &&
           foo.bar.baz.bat != null;
}
FishBasketGordo
  • 22,468
  • 4
  • 58
  • 91
2

This is a fairly frequently requested feature, and as a result this question has now been asked several times on StackOverflow. See

Shortcut for "null if object is null, or object.member if object is not null"

for some thoughts on it.

Community
  • 1
  • 1
Eric Lippert
  • 630,995
  • 172
  • 1,214
  • 2,051
2

Good question, but bad intentions. Your code is going to ignore the Law of Demeter

Igor Soloydenko
  • 9,597
  • 8
  • 44
  • 80