.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;
}
else
{
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”);