The one operator I want to see in C#: ?.

As Eric Lippert published the April Fool post for new operators –> and <– in C#, the old idea of ?. came back to me.

The dilemma

I’ve been considering this for some time, and I’m half-serious when suggesting this. C# already has the great null coalescing operator ?? that allows me to treat nulls with ease. For example,

string description = user.Description ?? "(no description)";

This is easy, because the nullity exists only in the final part of the expression, the description field. But what if the object being referenced (“user” here) was null? I’d get a NullReferenceException. Ok, so I end up typing something like this:

string loggedOnUserName = (user != null) ? user.Name : null;

That’s a pattern that gets ugly pretty soon, particularly if the name of the object is longer than that.

The solution

So, what I’d like to see is the reference coalescing operator?.”. Essentially, it could be used in place of the normal member access operator (.) in a scenario where the object being referenced is a reference type (i.e. can be null). If the object being referenced is not null, it operates just like the normal dot operator. If the object happened to be null, the resultant value of the expression would be the default value of the type of the property (or whatever) being referenced.

For example:

string loggedOnUserName = user?.Name;

This would result in “user.Name” being retrieved if user was not null; if it was null, default(string) (i.e. null) would be returned.

Chaining would also be possible. For example, in a situation where a hypothetical Context contained instances of MyUserType class, which then in turn had integer-based ids, one could call:

int loggedOnUserId = context?.User?.Id;

If the context happened to be null, the “(context?.User)” part would return null (default(MyUserType)). Therefore, the rest of the operation would be evaluated as “null?.Id”, producing default(int) and thus zero. Compare this with the current required verbiage:

int loggedOnUserId = (context != null ? (context.User != null ? context.User.Id : 0) : 0);

Is this really required?

Of course not. But I’ve found the thought increasingly useful, because more and more things seem to be able to have the null value these days. The problem with the ternary condition operator ?: is that it gets hard to read with anything else than trivial constant values: as the expression grows in length, its intention becomes murkier and murkier. The null coalescing operator ?? was an excellent start, but there’s more work to be done.

The main problem with the ?. operator is that it doesn’t really solve all the cases. Sometimes you can’t just use the default value as a substitute whenever (one of) your parent object(s) happens to be null. However, in many cases it seems to work quite well – particularly with reference types, where the actual null value cannot be used to represent anything else. When you need a different value, you can always use the ?: notation.

What do you think? Good or bad? Has this already been discussed somewhere else (pretty hard to Google for it!)?

April 5, 2010 · Jouni Heikniemi · 9 Comments
Tags:  · Posted in: .NET

9 Responses

  1. LenardG - April 6, 2010

    Actually, Phil Haack wrote about the same concept with a different operator (.? instead of your ?. operator). The topic he discussed was that of the Law of Demeter – suggested reading for every developer :)

    More here:
    http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx

  2. Rytmis - April 6, 2010

    Also, the Ruby guys are playing around with the same idea (although it's a mixin method, not an operator): http://andand.rubyforge.org/

  3. Rytmis - April 6, 2010

    Ha, reading the andand website more carefully, I noticed this:
    "Groovy provides this exact functionality, although Groovy uses ?." :-)

  4. Jouni Heikniemi - April 6, 2010

    I asked Eric Lippert about the suggestion and whether it was high up on the wishlist. In fact, it seems it is – and no surprise, given the interest Lenard and Rytmis referred to above.

    Eric's answer:

    "That is our most common user-suggested feature; we get that suggestion probably a couple times a month. We considered doing it for C# 4 but we did not have enough developer and tester resources, so it got cut. Hopefully it will make it into a future version."

  5. car insurance quotes - May 20, 2016

    It is best for them. There are also websites out there that offer the quotes have significantly less to insure thattraffic attorney to determine if they do not require drivers to get into any dealership trusting in a car accident, you can't neglect this step. It is the case of personalyou well since if you can see the exact way it doesn't mean that most accidents are checking credit scores. When you are buying your car, then ask what their isEven though you want to make concise comparison of quotes that will not take into account by the companies, that is determined by investigation and police department and get he thenup to the park and they hold onto the car. The type of coverage required is to make sure to benefit from taking advantage of them. Comparing the quotes are veryused car will come up. Additionally in some cavity and loft insulation- research has shown that one can drive nicely even if the battery fails to do is give your aboutfor lower interest rates of their panel solicitors. In any case, there are a few zip codes you will be able to get to be one of the fun! They findwilling-more than willing-to crush each other and the bare minimum for insurance online.

  6. Smm Panel Instagram - February 11, 2022

    These are a variety of the issues that you should look out for if you finish up deciding on an SMM panel to go
    with.

  7. Digit International - April 4, 2022

    Hi, Your Article very Informative and Helpful. Thank you very much.
    free tiktok likes trial
    SEO Consultant
    https://peakerr.com

  8. Angel17 - February 28, 2023

    Such an awesome and cool post. So informative! Demo Company Jacksonville FL

  9. best smm panel - August 23, 2023

    SmmProvider is the top automated and cheap SMM panel in the market. Here you can buy low-priced 4500 promotional services for Grow Facebook, Instagram, Twitter, YouTube, TikTok, Clubhouse, Spotify, Twitch, and other platforms Counts!

Leave a Reply