Are you looking for a short-circuited undefined member access operator ?. which was introduced in C # language version 6 (released in Visual Studio 2015).
The rest of my answer was written for earlier versions of C # that didn't have a statement ?. .
Generally speaking, if you are in a situation where you are accessing a deeply "nested" property, such as outermostObject.abcX , you should probably consider redesigning your code, since such access may indicate that you are violating the established principles of the TOE ( such as the principle of least knowledge, as well as the Law of Demeter).
Some other options:
First , anti-offer; do not do this:
string lname = null; try { lname = Person.Name.ToLower(); } catch (NullReferenceException ex) { }
Second , using something like Maybe monad - you can define this type yourself. This is basically a Nullable<T> that implements IEnumerable<T> so that it returns an empty sequence when no value is given, or a sequence of exactly one element if the value is set. Then you will use it as follows:
Maybe<string> personName = person.Name; var lname = (from name in personName select name.ToLower()).FirstOrDefault();
The third and perhaps the simplest and most practical solution suggested by ulrichb:
var lname = person.Name != null ? person.Name.ToLower() : null;
PS , since we are already talking about checking for null , do not forget to check if there is a person null before accessing the Name property ..; -)
stakx
source share