14

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.

4
  • 2
    Use Convert.ToString(a) instead of a.ToString() See stackoverflow.com/questions/2828154/… Commented Feb 5, 2014 at 15:36
  • 3
    @animaonline "How to convert nullable int to Google?" Commented Feb 5, 2014 at 15:37
  • 3
    Ignore the snarky coments. Apparently, they haven't read Kicking off the Summer of Love Commented Feb 5, 2014 at 15:37
  • I don't know if and when it changed, but ToString() does not throw an exception (anymore): learn.microsoft.com/en-us/dotnet/api/… Commented Feb 26, 2021 at 8:46

6 Answers 6

39

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;
Sign up to request clarification or add additional context in comments.

3 Comments

And how does Convert handle null? Does it return "null" as OP asked?
This answer explains how to handle the exception for a 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.
to be clearer,Convert.ToString(a) returns "" not null
5

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

string str = a.HasValue ? a.Value.ToString() : "Null";

1 Comment

this answer at least answers the question.
5

The shortest answer is:

int? a = null;
string aString = a?.ToString() ?? "null";

Comments

2

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.

Comments

2

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"

2 Comments

Given the down votes people clearly don't like the extension method approach!
(1) It was asked to make it without extension method, (2) int?.ToString() do exactly the same as this extension method.
0
if(a.HasValue())
{
   return a.Value().ToString();
}
return string.Empty;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.