3

Possible Duplicate:
Deep Null checking, is there a better way?

for example, if you are performing a logic on Foo1.Bar1.Foo2.Bar2 (and each of the properties can be null), you can't just do that to foo.Bar1.Foo2.Bar2 because it is possible that you get null reference exception

Currently this is what I do

if (foo1!=null && foo1.Bar1!=null && foo1.Bar1.Foo2 !=null && foo1.Bar1.Foo2.Bar2!=null)
return DoStuff(foo1.Bar1.Foo2.Bar2); //actually a logic based on the value of Bar2
else return null; 

Is there a more elegant or convenient way, to do this?

Community
  • 1
  • 1
Louis Rhys
  • 34,517
  • 56
  • 153
  • 221

3 Answers3

0

No, there isn't.

The only thing that might help, is to evaluate if DoStuff is actually defined in the right class.

Willem van Rumpt
  • 6,490
  • 2
  • 32
  • 44
0

this extention method work but is not cool code or may be can improve it:

public static bool AnyNull<TSource, TResult>(this TSource source, Func<TSource, TResult> selector)
        {
            try
            {
                selector(source);
                return false; ;
            }
            catch { return true; }
        }

use it:

if(!foo1.AnyNull(p=>p.Bar1.Foo2.Bar2))
    DoStuff(foo1.Bar1.Foo2.Bar2)
Reza ArabQaeni
  • 4,848
  • 27
  • 46
0

No, unfortunately there isn't. I too have often wished for a simpler syntax!

However, here's a pretty decent alternative that I came up with: create an Null-Safe-Chain helper method. Here's what it looks like:

var bar2 = NullSafe.Chain(foo1, f1=>f1.Bar1, b1=>b1.Foo2, f2=>f2.Bar2);

Here's the method:

public static TResult Chain<TA,TB,TC,TResult>(TA a, Func<TA,TB> b, Func<TB,TC> c, Func<TC,TResult> r) 
where TA:class where TB:class where TC:class {
    if (a == null) return default(TResult);
    var B = b(a);
    if (B == null) return default(TResult);
    var C = c(B);
    if (C == null) return default(TResult);
    return r(C);
}

I also created a bunch of overloads (with 2 to 6 parameters). This works really well for me!

Scott Rippey
  • 15,614
  • 5
  • 70
  • 85