Object - ToStringSafe

An object extension method that converts the @this to string or return an empty string if the value is null.

Try it

public static void Main()
{
    int thisValue = 1;
    string thisNull = null;

    // C# Extension Method: Object - ToStringSafe
    string result1 = thisValue.ToStringSafe(); // return "1";
    string result2 = thisNull.ToStringSafe(); // return "";

    Console.WriteLine(result1);
    Console.WriteLine(result2);
}

View Source
public static partial class Extensions
{
    /// <summary>
    ///     An object extension method that converts the @this to string or return an empty string if the value is null.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a string or empty if the value is null.</returns>
    public static string ToStringSafe(this object @this)
    {
        return @this == null ? "" : @this.ToString();
    }
}