C# methods of converting a null string to an empty string

One really cool feature of the .NET Framework is the ability to create extension methods.  If you’ve used the .NET Framework then you have most likely used extension methods and realize the power of them.  There are many existing extension methods for the string type, such as Trim, Substring or ToUpper.  You can create your own extension methods to simply development!

I noticed found myself constantly writing code to check strings for null and converting the string to empty if it is null.  There are a number of ways to code this but I used to use Method 2 below.

Using Extension Methods in C#

// Method 1

myval  = myval + "";

// Method 2

myval = inputvar ?? String.Empty;

// Method 3 – New Extension Method EmptyIfNull

// Use the NEW extension method shown below. Notice that there are NO arguments but the extension method below has one argument of type string.  The argument is being passed to the new extension method via the string to the left of the dot.  You could think of the function as EmptyIfNull(myval) as it is essentially the same thing!

myval = myval.EmptyIfNull();

The New Extension Method To Convert Null Strings To Empty

The code below makes an extension method for type string.  After writing this function we can use this extension method simply by putting a dot after a string and then typing the function name.

The secret to making an extension method work is the “this” keyword. Notice that the parameter to the function is “this string value”.  The this keywords allows you to call this extension method from a string class without passing any argument.  The this keyword refers to the string for which you are applying the extension method to.

Another key part to making extension methods work is that they must be defined as static and within a non-specific static class.

namespace LinkDBuilder.Utility
    public static class Extensions
        public static string EmptyIfNull(this string value)
         if (value == null)
              return System.String.Empty;
           return value;

.NET Extension Methods Can Be Chained Together

I personally think extension methods are easier to read then a global function. Many times I find myself combining many extension methods. The examples below use the new EmptyIfNull extension method in combination with .NET Frameworks existing extension methods “Trim”, “Substring” and “ToUpper”.


mystring.EmptyIfNull().Trim().Substring(1, 10).ToUpper();


No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *