Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nullable numeric into string

I want to convert a nullable numeric into a string maintaining the null value. This is what I'm doing:

int? i = null;
string s = i == null ? null : i.ToString();

Is there something shorter?

like image 392
Clodoaldo Neto Avatar asked Jul 13 '12 14:07

Clodoaldo Neto


1 Answers

You can write some extension method:

public static string ToNullString(this int? i)
{
   return i.HasValue ? i.ToString() : null;
}

Usage will be more simple:

string s = i.ToNullString();

Or generic version:

public static string ToNullString<T>(this Nullable<T> value)
    where T : struct
{
    if (value == null)
        return null;

    return value.ToString();
}
like image 198
Sergey Berezovskiy Avatar answered Sep 19 '22 22:09

Sergey Berezovskiy