String extension that returns a default value when empty

Posted: June 12, 2011 in .NET
Tags: , ,
.Net Framework Logo

Image via Wikipedia

.NET extension methods are very useful. Here is one that I am using frequently in a current project –

I want to trim a string of extra spaces at the ends, then check to see if it is empty. If it is empty I want to assign a default value.

With .NET extension methods, it makes it easy to create a peice of reusable code that can be called like any method.

    public static class StringExtensions
        /// <summary>
        /// If the current string (trimmed) is empty then return the default string
        /// </summary>
        /// <param name=”currentString”>The current string value</param>
        /// <param name=”defaultString”>The string to return if the current string is empty</param>
        /// <returns></returns>
        public static string DefaultIfEmpty(this string currentString, string defaultString)
            if (currentString.Trim() == string.Empty)
                return defaultString;
                return currentString.Trim();

The preceding word ‘this’ in the parameter declaration means that you can call this method on any string.

Example using the new extension –

string myString = ” “;

myString.DefaultIfEmpty(“I was empty”);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s