I would like to ask for any tips how to improve the code in case of cascade of conditions, where you have to ask if the property inside of property is not null.
Just simple dummy example:
public class ClassA
{
public ClassB classB { get; set; }
}
public class ClassB
{
public List<ClassC> classesC { get; set; }
}
public class ClassC
{
public ClassD classD { get; set; }
}
public class ClassD
{
public string value { get; set; }
}
Then let's say you want to get such a value: classA.classB.classesC.First().classD.value;
Is there any efficient way to do that and be sure you won't get the error, when any of these classes is null? Instead of many conditions:
if (classA != null && classA.classB != null && classA.classB.classesC != null && classA.classB.classesC.First() != null && classA.classB.classesC.First().classD != null) return classA.classB.classesC.First().classD.value;
Just note, I'm not looking for solution to use try
block and catch NullException.
Thanks.
You can use the null conditional operator, ?.
Note that you'll probably also want to use FirstOrDefault()
rather than First()
: First()
will throw if the collection is empty, but FirstOrDefault()
will return the default value (null
in the case of reference types).
var result = classA?.classB?.classesC?.FirstOrDefault()?.classD?.value;
if (result != null)
{
return result;
}
You can combine this with a simple pattern to simplfy things a bit:
if (classA?.classB?.classesC?.FirstOrDefault()?.classD?.value is { } x)
{
return x;
}
The { }
pattern here means "an object which isn't null".