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 declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
.ToString()It will not handle NULL values; it will throw a NULL reference exception error. 2. We can use anytime (even null). 2.
In C# 8.0, strings are known as a nullable “string!”, and so the AllowNull annotation allows setting it to null, even though the string that we return isn't null (for example, we do a comparison check and set it to a default value if null.) This is a precondition.
Nullable types are neither value types nor reference types.
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'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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With