I need to convert the nullable int to string
int? a = null;
string str = a.ToString();
How can I perform this action without an exception? I need to get the string as "Null". Please guide me.
I need to convert the nullable int to string
int? a = null;
string str = a.ToString();
How can I perform this action without an exception? I need to get the string as "Null". Please guide me.
You can simply use the Convert.ToString()
which handles the null values as well and doesn't throw the exception
string str = Convert.ToString(a)
Or using if
condition
if(a.HasValue)
{
string str = a.Value.ToString();
}
Or using ?
Ternary operator
string str = a.HasValue ? a.Value.ToString() : string.Empty;
If you really need the string as "Null" if a
is null
:
string str = a.HasValue ? a.Value.ToString() : "Null";
I like to create an extension method for this as I end up doing it over and over again
public static string ToStringNullSafe<T>(this T value)
{
if(value == null)
{
return null;
}
else
{
return value.ToString();
}
}
You can obviously create an overload with a format string if you wish.
I'd create an extension method as well, but type it off of Nullable and not any T.
public static string ToStringOrEmpty<T>(this T? t) where T : struct
{
return t.HasValue ? t.Value.ToString() : string.Empty;
}
// usage
int? a = null;
long? b = 123;
Console.WriteLine(a.ToStringOrEmpty()); // prints nothing
Console.WriteLine(b.ToStringOrEmpty()); // prints "123"