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!
David Jedziniak maintains this blog and posts helpful tips and tricks on SQL Server and Dynamics GP development. The opinions expressed here are those of the author and do not represent the views, express or implied, of any past or present employer. The information here is provided without warranty of fitness for any particular purpose.
Friday, March 27, 2015
Subscribe to:
Post Comments (Atom)
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 ...
-
If you are reading this, you are probably aware of the fact that you cannot deploy SSRS 2008 reports on an SSRS2005 server. SSRS reports ar...
-
SQL Job to refresh TEST from PRODUCTION Last Updated: 2018.11.12 I like to include each of these steps as a separate job step. If you ...
-
I ran into an issue today where I had a report parameter default that I couldn't seem to get rid of. In BIDS, I deleted the defaults f...
No comments:
Post a Comment