My new favorite C# operator: The null coalesce operator (??)

Up until now my favorite operator was probably the ternary operator. Not that I’ve spent a lot of time thinking about it. It is kinda weird to have a favorite operator, I suppose. But hey, strange things happen to the minds of people who write software for a living.

Today I was writing some web app code, I found myself thinking “gee, I wish there was a some way that C# that would let me set my variable to the first thing in my list that’s not null.”

For some reason I searched google for it. And it exists! Somewhere, some crazy language specification researcher managed to get this idea past his boss.

For those who may not be aware, there is an extremely useful SQL statement called COALESCE, which returns the first argument in it’s argument list that’s not null. Very useful when formatting columns that may be null or when left joining tables. Like the SQL statement, this C# operator won’t be used THAT often. But, when you need it, it’s really handy to have.

It works like this. Instead of writing:
Control c = null;
c = FindControl("control1");
if (c == null)
    c = FindControl("control2");

I can write:
Control c;
c = FindControl("control1") ?? FindControl("control2");

To me, the ?? version is a bit more readable, and makes the logic easier to understand.


  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: