Continue if not null operator? Yes please!

Olmo made a very worthwhile suggestion on the LINQ forums recently. His suggestion was for a new operator to be added to the C# language to allow us to do away with the following kind of pesky construct:

string x;
if(a != null && a.Address != null && a.Address.FirstLine != null)
    x = a.Address.FirstLine;

instead he suggested a new ?. operator so that we could produce something like this:

x = a?.Address?.FirstLine;

and at the first sign of failure it would just yield a null or the equivalent. I like this suggestion, it is elegant, and provides a similar meaning to the coalescing operator. The C# team have been adding lots of these little bits of syntactic sugar recently, so why not add another that will save us lots of thrown exceptions or grisly if statements?


9 thoughts on “Continue if not null operator? Yes please!

  1. Good suggestion.

    I’d also like:
    if (a == Blah.Foo || a == Blah.Bar)
    To become:
    if (a == Blah.Foo || Blah.Bar)

    if (a > min && a < max)
    if (min < a < max)

  2. Hi Paul,

    that first one would never get off the ground – they’d have to change the logic of the compiler to ignore the interpretation of the second term in the expression as a bool, and to convert it to a more complex structure during compile time. How would you ever know which interpretation the user really wanted?

    The second one would make sense and could be complemented by all the other mathematical inequalities for <= & >= etc


  3. C and C++ used

    if (a && a.Address && a.Address.FirstLine)
    x = a.Address.FirstLine;


  4. Andy E,

    Same with your suggestion – C & C++ got away with that sort of solution because they were loosely typed and could convert pointers and most other types into bools. C# is much stronger in the typing department and to get it to make sense of that kind of formation would require a loosening of the type safety of the language, which I for one wouldn’t like to see.

    besides, I like the idea of being able to do it in one line!


  5. Hi Tatham,

    Not sure – you’re the ex Microsoftie aren’t you? You should be telling me (or pulling strings) 😉
    I’d definitely put it forward if there was a place for me to do that. Is Connect that place?


  6. For small / home projects this would rock.

    For commercial / enterprise apps this just strikes me as seven shades of badness just waiting to creep up on you when you least expect it.

    It falls into the basket of features that I would barely trust myself to use correctly let alone some poor intern.

  7. I can speak from bitter recent experience that you can’t trust an intern to do anything right, even with a language that doesn’t have useful operators…

Comments are closed.

Create a website or blog at

Up ↑

%d bloggers like this: