James Andrew Smith James Andrew Smith - 16 days ago 5
ASP.NET (C#) Question

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.

Answer
static string NullToString( object Value )
{

    // Value.ToString() allows for Value being DBNull, but will also convert int, double, etc.
    return Value == null ? "" : Value.ToString();

    // If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast
    // which will throw if Value isn't actually a string object.
    //return Value == null || Value == DBNull.Value ? "" : (string)Value;


}