Wednesday, April 16, 2008

string.GetValueOrDefault() - A Simple Extension Method

I have found that, I have written codes like the following one in my projects before now at some places.

string myString = someString == null ? string.Empty : someString;

However, with the advent of extension methods in C# 3.0 (.Net 3.5), I have a better way of achieving this goal in my projects. So, I just wrote an extension method as the following one-

public static class StringExtensions
{
public static string GetValueOrDefault(this string instance)
{
return instance == null ? string.Empty : instance;
}
}

Well, I have just borrowed the name of the method from the Nullable type and think this name means its purpose to the fullest!

However, with this addition, I can now rewrite my code example as the following one-

string myString = someString.GetValueOrDefault();

Happy coding!