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;
Convert handle null? Does it return "null" as OP asked?null value. Once you handle it then you can put your logic to get any value (e.g. "Null" from any of the options mentioned above.Convert.ToString(a) returns "" not nullIf you really need the string as "Null" if a is null:
string str = a.HasValue ? a.Value.ToString() : "Null";
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"
ToString()does not throw an exception (anymore): learn.microsoft.com/en-us/dotnet/api/…