We have a lot of confortable methods ready to use in our .NET objects and this is wonderful: just think for example the method .toString()! How much do we use it? But, sometimes, these methods aren’t enough and we need to create others on our own.

In this post I show how to create an extesion method useful to create a more powerful version of the classic toString method. Normally, the toString method fails if you have a null value in the string. With this method, if the value is null, it doesn’t throw any error/exception but it returns the string “NULL”.

public static class Extensions
{
    public static string ToSafeString(this object obj)
    {
        return (obj ?? "NULL").ToString();
    }
}

Note:

  1. The class has to be static (or shared in VB.NET)
  2. Also the method has to be static (or shared in VB.NET)
Advertisements