A non-repetitive way to say: access this object if the object is not null
Let's say I have a set of cars where each car has a steering wheel. I would like to write a line of code that looks for a car in the kit and returns its steering wheel, or returns null if the car is not in the kit. Something like that:
Car found = // either a Car or null
SteeringWheel wheel = (found == null ? null : found.steeringwheel);
Is there a way to do this without using found
and null
twice in the expression? I don't like the smell of repetition here.
+3
source to share
3 answers
There is no obvious improvement until C # 6 arrives, but until then, you can hide the nuisance in the extension method.
void Main() {
Car found = null;// either a Car or null
SteeringWheel wheel = found.MaybeGetWheel();
}
public static class CarExtensions {
internal static SteeringWheel MaybeGetWheel(this Car @this) {
return @this != null ? @this.steeringwheel : null;
}
}
Some say you shouldn't let extension methods be called null
, but it works. This is a style preference, not a technical limitation.
+3
source to share