4

Is there a way to do a generic cascading null reference check in c#?

What i am trying to achieve is if i am trying to access a string variable which is part of a class C, which is inturn in class B, which is in A.

A.B.C.str

And that i am passed in A, i will have to check to see if A is null, then check if B is null, then check is C is null and then access str.

Is it possible to have some method where - we can potentially pass in, A and A.B.C.str and it return null is anything was null or value of str if everything existed correctly.

5
  • 4
    I smell a Law of Demeter violation. Jun 25, 2014 at 20:26
  • I've done something nasty here: stackoverflow.com/questions/17657942/…
    – rene
    Jun 25, 2014 at 20:28
  • @rene: That is so wrong in so many ways. I think I like it. Jun 25, 2014 at 20:29
  • 3
    It would be better to figure out where those nulls are coming from - and stop them near the source. Jun 25, 2014 at 20:34
  • @RobertHarvey thanks for the compliment :-)
    – rene
    Jun 25, 2014 at 20:38

2 Answers 2

6

There is no built in way to do this yet, however in C# 6.0 we are expecting a 'safe navigation' operator, see this post by Jerry Nixon

It will look something like this:

var g1 = parent?.child?.child?.child; 
if (g1 != null) // TODO
5
  • FTFY .......... meta.stackexchange.com/questions/8231/… Jun 25, 2014 at 20:33
  • 2
    Exactly what i was hoping for today :) That is awesome .. can't wait for c# 6 then!!!
    – MoXplod
    Jun 25, 2014 at 20:35
  • Same. The old way of checking each level will still be widely used for obvious reasons but it will definitely clean up some portions of code. In Nixon's post, however, it does not definitively say whether or not this will be in 6.0 or not.
    – GEEF
    Jun 25, 2014 at 20:36
  • 3
    @VP. according to the Roslyn status page, it's ready and will be included: roslyn.codeplex.com/… Jun 25, 2014 at 20:43
  • You can already do this in .NET 4.0 or at least you can with .NET 4.0 with VS2015
    – fkerrigan
    Apr 18, 2016 at 10:56
3

There is no built-in possibility in c#, but you can use something like this http://www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad

It involves declaring a function thusly:

public static TResult With<TInput, TResult>(this TInput o, 
       Func<TInput, TResult> evaluator)
       where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}

which you can then call like this:

string postCode = this.With(x => person)
                      .With(x => x.Address)
                      .With(x => x.PostCode);
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.