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?

About these ads

9 comments

  1. Good suggestion.

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

    And:
    if (a > min && a < max)
    To:
    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

    Andrew

  3. 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!

    Andrew

  4. 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?

    Andrew

  5. 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.

Comments are closed.