Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert nullable int to string

Tags:

c#

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.

like image 624
Ravi Shankar B Avatar asked Feb 05 '14 15:02

Ravi Shankar B


People also ask

How do you create a nullable string?

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.

Can you ToString a null?

.ToString()It will not handle NULL values; it will throw a NULL reference exception error. 2. We can use anytime (even null). 2.

Are there nullable strings?

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.

Is nullable int a value type?

Nullable types are neither value types nor reference types.


3 Answers

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;
like image 87
Sachin Avatar answered Oct 21 '22 14:10

Sachin


If you really need the string as "Null" if a is null:

string str = a.HasValue ? a.Value.ToString() : "Null";
like image 25
Roland Bär Avatar answered Oct 21 '22 13:10

Roland Bär


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"
like image 32
DavidN Avatar answered Oct 21 '22 13:10

DavidN