Code Tips

Code Tip: C# Coalesce

I have to admit something. I’m something of a Sql Coalesce() fan. I know that Sql Server has an IsNull() function, but there are two bad things about it. First, it is proprietary to Sql Server and I like to try to write my Sql as close to ANSI as I can so that I don’t build up too many bad habits that cause me to have problems when I have to work in other DB platforms. Secondly, IsNull() only takes one option (well, you could nest your IsNull() statements, but that is unwieldy). Coalesce() lets you give a list of items and just takes the first one of them to not be null. Apparently, IsNull() is also slower. All hail, Coalesce()!!!

Several months ago, I was doing some coding in C# and I was actually wishing that C# had a Coalesce function so that I could not have to do a bunch of manual null checking in my code. On a whim, I decided to Google C# Coalesce and see if someone had written one or if there was one hidden in the framework somewhere. To my surprise, I found that C# did have such an animal. Here is an example of its use.

// Checks the HTML Form for a value,
// if that wasn't submitted, use the value
// potentially set elsewhere in the code,
// if that is null, set the variable to
// a blank string.
string value = Request.Form["someField"] as string ?? someVariable ?? string.Empty;

I can’t tell you how much I love having this.

One comment Code Tip: C# Coalesce

Alex says:

I love me some coalesce too. I came across it some time last summer when I really needed a good search stored procedure. I’ve written some pretty hideous search procs because of this problem. Now, they are very elegant, and fast! Now, I am using them in my front end apps as well.

I’m with you: All hail, Coalesce()!!!

Comments are closed.