Friday, March 27, 2015

Coalesce in C#

I ran into an interesting issue today with string math, which enlightened me to a shortcut function in C# that works similarly to the T-SQL function COALESCE.

I was appending strings to StringBuilders and adding strings using string math.  Something like this:

string header=getheader();
string footer=getfooter();
StringBuilder body=new StringBuilder ();
string value1=getvalue1();
string value2=getvalue1();

body.append(header);
body.append(value1 + value2);
body.append(footer);

return body.ToString();

I expected this to always return a string.
However, if value1 is null, there is no error thrown.
The return value is simply null...even if all the other variables have valid strings.

Normally, I would add a function that accepts a string, tests for null, and returns string.empty, as follows:

private static string TestNull(string value){
if(value==null){
return string.empty;
}
else{
return value;
}
}

But what if I want to make it some other value than string.empty?  And what if I need to test that value too?  Now it gets a bit messy.

I remembered the COALESCE operator in T-SQL.

COALESCE makes this clean by letting you do things like this:
select COALESCE(field1,field2,@myfield,'')
The above statement will roll through the values from left to right and use the first one that is not null.

I thought, maybe there is a built in function for handling this in C#.  Google brought forth the golden egg.

?? (null-coalescing operator)

In C#, this operator basically says if the string on the left is null, use the string on the right.  And it can be daisy-chained.

so I can say something like this:
 value1=value2 ?? header ?? string.empty;

Happy coalescing!

No comments:

Post a Comment

SQL 2022 TSQL snapshot backups!

  SQL 2022 now actually supports snapshot backups!  More specifically, T-SQL snapshot backups. Of course this is hardware-dependent. Here ...