You are looking for the short-circuiting null-conditional member access operator ?.
that was introduced in C# language version 6 (rolled out in Visual Studio 2015).
The remainder of my answer was written for earlier versions of the C# language which did not have the ?.
operator.
Generally speaking, if you're in a situation where you are accessing a deeply "nested" property, such as outermostObject.a.b.c.X
, you should probably consider re-designing your code, as such an access could indicate that you're violating established OO principles (such as the principle of least knowledge, a.k.a. Law of Demeter).
Some other options:
First, an anti-suggestion — don't do this:
string lname = null;
try
{
lname = Person.Name.ToLower();
}
catch (NullReferenceException ex) { } // inefficient and ugly
Second, using something like a Maybe
monad — you can define such a type yourself. It's basically a Nullable<T>
that implements IEnumerable<T>
such that it returns an empty sequence when no value is set, or a sequence of exactly one element if a value is set. You'd then use it as follows:
Maybe<string> personName = person.Name;
var lname = (from name in personName select name.ToLower()).FirstOrDefault();
Third, and probably the easiest and most practical solution, as suggested by ulrichb:
var lname = person.Name != null ? person.Name.ToLower() : null;
P.S., since we're already on the topic of checking for null
, don't forget to check whether person
is null
before accessing its Name
property... ;-)