James Andrew Smith James Andrew Smith - 1 year ago 155
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
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 Source
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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download