[c#] A function to convert null to string

I want to create a function to convert any null value e.g. from a database to an empty string. I know there are methods such as if value != null ?? value : String.Empty but is there a way to pass null to a method e.g.

public string nullToString(string? value)
{
    if(value == null) return empty;
    return value
}

But I am not sure on the parameter syntax to do this..

I tried the above but it says not a nullable type.

Thanks in advance.

This question is related to c# asp.net

The answer is


You can use Convert.ToString((object)value). You need to cast your value to an object first, otherwise the conversion will result in a null.

using System;

public class Program
{
    public static void Main()
    {
        string format = "    Convert.ToString({0,-20}) == null? {1,-5},  == empty? {2,-5}";
        object nullObject = null;
        string nullString = null;

        string convertedString = Convert.ToString(nullObject);
        Console.WriteLine(format, "nullObject", convertedString == null, convertedString == "");

        convertedString = Convert.ToString(nullString);
        Console.WriteLine(format, "nullString", convertedString == null, convertedString == "");

        convertedString = Convert.ToString((object)nullString);
        Console.WriteLine(format, "(object)nullString", convertedString == null, convertedString == "");

    }
}

Gives:

Convert.ToString(nullObject          ) == null? False,  == empty? True 
Convert.ToString(nullString          ) == null? True ,  == empty? False
Convert.ToString((object)nullString  ) == null? False,  == empty? True

If you pass a System.DBNull.Value to Convert.ToString() it will be converted to an empty string too.


Its possible to make this even shorter with C# 6:

public string NullToString(string Value)
{
    return value?.ToString() ?? "";
}

According to the following MSDN page, you need the Convert.ToString method

string x = Convert.ToString((object)value)

You can just use the null coalesce operator.

string result = value ?? "";

 public string ToString(this string value)
        {
            if (value == null)
            {
                value = string.Empty;
            }               
            else
            {
                return value.Trim();
            }
        }

public string nullToString(string value)
{
    return value == null ?string.Empty: value;   
}

Sometimes I just append an empty string to an object that might be null.

object x = null;
string y = (x + "").ToString();

This will never throw an exception and always return an empty string if null and doesn't require if then logic.


It is possible to use the "?." (null conditional member access) with the "??" (null-coalescing operator) like this:

public string EmptyIfNull(object value)
{
    return value?.ToString() ?? string.Empty;
}

This method can also be written as an extension method for an object:

public static class ObjectExtensions
{
    public static string EmptyIfNull(this object value)
    {
        return value?.ToString() ?? string.Empty;
    }
}

And you can write same methods using "=>" (lambda operator):

public string EmptyIfNull(object value)
    => value?.ToString() ?? string.Empty;

Its an old topic, but there is a "elegant" way to do that...

static string NullToString( object Value )
{       
    return Value = Value ?? string.Empty;    
}

Convert.ToString(object) converts to string. If the object is null, Convert.ToString converts it to an empty string.

Calling .ToString() on an object with a null value throws a System.NullReferenceException.

EDIT:

Two exceptions to the rules:

1) ConvertToString(string) on a null string will always return null.

2) ToString(Nullable<T>) on a null value will return "" .

Code Sample:

// 1) Objects:

object obj = null;

//string valX1 = obj.ToString();           // throws System.NullReferenceException !!!
string val1 = Convert.ToString(obj);    

Console.WriteLine(val1 == ""); // True
Console.WriteLine(val1 == null); // False


// 2) Strings

String str = null;
//string valX2 = str.ToString();    // throws System.NullReferenceException !!!
string val2 = Convert.ToString(str); 

Console.WriteLine(val2 == ""); // False
Console.WriteLine(val2 == null); // True            


// 3) Nullable types:

long? num = null;
string val3 = num.ToString();  // ok, no error

Console.WriteLine(num == null); // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False 

val3 = Convert.ToString(num);  

Console.WriteLine(num == null);  // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False

You can try this

public string ToString(this object value)
{
    // this will throw an exception if value is null
    string val = Convert.ToString (value);

     // it can be a space
     If (string.IsNullOrEmpty(val.Trim()) 
         return string.Empty:
}
    // to avoid not all code paths return a value
    return val;
}

When you get a NULL value from a database, the value returned is DBNull.Value on which case, you can simply call .ToString() and it will return ""

Example:

 reader["Column"].ToString() 

Gets you "" if the value returned is DBNull.Value

If the scenario is not always a database, then I'd go for an Extension method:

public static class Extensions
{

    public static string EmptyIfNull(this object value)
    {
        if (value == null)
            return "";
        return value.ToString();
    }
}

Usage:

string someVar = null; 
someVar.EmptyIfNull();

1. string.Format

You can use string.Format which converts null to empty string

string nullstr = null;
string  quotestring = string.Format("{0}", nullstr);
Console.WriteLine(quotestring);//Output- ""

2.string interpolation

or you can use string interpolation. this feature is available in C# 6 and later versions.

InterpolatedExpression produces a result to be formatted. A string representation of the null result is String.Empty.

 string nullstr = null;
 string  quotestring = $"{nullstr}";
 Console.WriteLine(quotestring);//Output- ""

you can use ??"" for example:

y=x??""

if x isn't null y=x but if x is null y=""