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:
c = FindControl("control1") ?? FindControl("control2");
To me, the ?? version is a bit more readable, and makes the logic easier to understand.