They think of everything!

Ordinarily I like to pontificate on the merits (or detriments) of particular code design decisions. Instead today, I’d like to share a neat consequence of C# 6 that I found the other day.

We’re all familiar with the null-conditional operator ?. when accessing members (properties/functions). What you may not immediately see is the ability to use the ? when accessing an object via indexers. Check it out:

var value = myObj?[5];

As you might expect, this line of code returns myObj[5] when myObj is not null, or null if it is.

What I find interesting is that reading the code, it makes sense, but it’s not something that I immediately considered when learning about the ?. operator.

I guess what’s really happening here is that the real operator isn’t ?. but merely another use forĀ ?(the other use being the conditional operator which is combined with :). After this operator, you can access the data on the object, and it magically checks for null before proceeding with the access!


After writing this, I thought it sounded like I’m a total noob to .Net. I don’t even care. It’s nice that I can still learn basic things.

3 thoughts on “They think of everything!

  1. I think the biggest difference between coders you like working with and coders you don’t is directly related to how willing they are to learn.

    Some guys learn a lot and can’t be taught, and others realize there’s way too much to learn and no one can ever know it all.

    Just this week, I’ve learned a few things about MEF I’ve never known and I’ve been using it since around 2010. Who knew?

    I wish I could say I knew this, but I too thought the operator was ?. and it never occurred to me to use it differently. How did you discover this index accessibility feature?

    Like

    1. It was just one of those “What does this button do?” moments. I had an array that I was trying to index, but I received a NullReferenceException. I thought, “I wonder if this works…” and it did.

      Liked by 1 person

Leave a comment