3

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.

Joe
  • 3,804
  • 7
  • 35
  • 55

3 Answers3

7

You could wait a bit for C# 6.0, and then use null-conditional (a.k.a. safe navigation) operator, ?.:

SteeringWheel wheel = FindCar()?.steeringwheel;
AlexD
  • 32,156
  • 3
  • 71
  • 65
3

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.

recursive
  • 83,943
  • 34
  • 151
  • 241
0

Using linq you could do

var steeringwheel = cars.Where(c => c.name = "foo")
                        .Select(c => c.steeringwheel)
                        .SingleOrDefault();
T I
  • 9,785
  • 4
  • 29
  • 51