Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

?? Coalesce for empty string?

Something I find myself doing more and more is checking a string for empty (as in "" or null) and a conditional operator.

A current example:

s.SiteNumber.IsNullOrEmpty() ? "No Number" : s.SiteNumber; 

This is just an extension method, it's equivalent to:

string.IsNullOrEmpty(s.SiteNumber) ? "No Number" : s.SiteNumber; 

Since it's empty and not null, ?? won't do the trick. A string.IsNullOrEmpty() version of ?? would be the perfect solution. I'm thinking there has to be a cleaner way of doing this (I hope!), but I've been at a loss to find it.

Does anyone know of a better way to do this, even if it's only in .Net 4.0?

like image 387
Nick Craver Avatar asked Mar 10 '10 20:03

Nick Craver


People also ask

Does coalesce work with empty strings?

The Coalesce function evaluates its arguments in order and returns the first value that isn't blank or an empty string. Use this function to replace a blank value or empty string with a different value but leave non-blank and non-empty string values unchanged.

Can coalesce return NULL?

If all the values in MySQL COALESCE() function are NULL then it returns NULL as the output. It means that this function does not find any non-NULL value in the list.

How do you replace NULL values in a string in SQL?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.

Is NULL vs coalesce?

Comparing COALESCE and ISNULL Data type determination of the resulting expression is different. ISNULL uses the data type of the first parameter, COALESCE follows the CASE expression rules and returns the data type of value with the highest precedence.


1 Answers

C# already lets us substitute values for null with ??. So all we need is an extension that converts an empty string to null, and then we use it like this:

s.SiteNumber.NullIfEmpty() ?? "No Number"; 

Extension class:

public static class StringExtensions {     public static string NullIfEmpty(this string s)     {         return string.IsNullOrEmpty(s) ? null : s;     }     public static string NullIfWhiteSpace(this string s)     {         return string.IsNullOrWhiteSpace(s) ? null : s;     } } 
like image 65
D'Arcy Rittich Avatar answered Sep 30 '22 07:09

D'Arcy Rittich