Let's say I have a set of cars, where each car has a steering wheel. I'd like to write a line of code that looks for a car in the set and returns its steering wheel, or returns null if the car isn't in the set. Something like this:
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 the repetition here.
There's not an obvious improvement until c# 6 arrives, but you could hide the unpleasantness in an extension method until then.
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 people say that you shouldn't allow extension methods to be called on null
, but it does work. That's a style preference, not a technical limitation.