MoXplod
MoXplod

Reputation: 3852

Cascading null reference exception check?

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.

Upvotes: 4

Views: 1501

Answers (2)

GEEF
GEEF

Reputation: 1185

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

Upvotes: 6

IL_Agent
IL_Agent

Reputation: 747

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);

Upvotes: 3

Related Questions