Text Helper Utility Part 1: C# Coalesce
I thought that I should start with something simple, yet useful, to get the blogging juices flowing. So I'm going to write about some of the utility and helper classes I deal with on a day to day basis; The TextHelper.
TextHelper is static helper class containing useful methods for dealing with text and strings.
Existing language functionality:
The first method, and the one I use the most, is a spin off of the Transact-SQL COALESCE function. It adheres to the same principle as the SQL version in that it takes a variable number of arguments, and returns the first non-null, and in our case non-empty, argument. The T-SQL version is used along the lines of:
COALESCE([Col0], [Col1], 'None')
Since C# 2.0, we've also had the coalesce operator;
a very handy operator, which can save a lot of if ... else
statements.
It is used to return the first object that is not null like so:
MyObject a = null;
MyObject b = new MyObject();
MyObject c = a ?? b;`
In the example above, b
is the first non-null argument, and is
assigned to the variable c
.
Why another Coalesce method?
The difference between the aforementioned two methods and the TextHelper.Coalesce method is that they only deal with null values, but we often want null and empty to be considered the same when dealing with User Interfaces. Consider the following example of getting a contact number to display.
string phone = TextHelper.Coalesce(customer.Phone, customer.Mobile, "None Available");
Now when the customer
has a empty phone number, the mobile number is
returned, and if no mobile number is specified, "None Available" is used
as an indicator.
Source Code:
Here's the code extract from the text helper class.
public static class TextHelper
{
public static string Coalesce(params string[] args)
{
string value = string.Empty;
foreach (string arg in args)
{
if (!string.IsNullOrEmpty(arg))
{
value = arg;
break;
}
}
return value;
}
}
It's an extremely simple method and simply helps cut down on writing more lines of code than are necessary.
It also makes dealing with configuration "AppSetting" a little simpler too e.g.
string setting = TextHelper.Coalesce(ConfigurationManager.AppSettings["MyAppSettingKey"], "My Default Value");
What's Next?
Next time I'll be adding another simple method from the TextHelper class that separates cased words. Handy for displaying PascalCased enum strings and the like.