Reputation: 482
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.
Upvotes: 14
Views: 28190
Reputation: 1274
The shortest answer is:
int? a = null;
string aString = a?.ToString() ?? "null";
Upvotes: 5
Reputation: 367
if(a.HasValue())
{
return a.Value().ToString();
}
return string.Empty;
Upvotes: 0
Reputation: 40970
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;
Upvotes: 39
Reputation: 1730
If you really need the string as "Null" if a
is null
:
string str = a.HasValue ? a.Value.ToString() : "Null";
Upvotes: 5
Reputation: 5197
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"
Upvotes: 2
Reputation: 10191
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.
Upvotes: 2