13

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.

RBT
  • 24,161
  • 21
  • 159
  • 240
Ravi Shankar B
  • 472
  • 2
  • 4
  • 15
  • 2
    Use Convert.ToString(a) instead of a.ToString() See http://stackoverflow.com/questions/2828154/difference-between-convert-tostring-and-tostring – David Feb 05 '14 at 15:36
  • 3
    @animaonline "How to convert nullable int to Google?" – Uwe Keim Feb 05 '14 at 15:37
  • 3
    Ignore the snarky coments. Apparently, they haven't read [Kicking off the Summer of Love](http://blog.stackoverflow.com/2012/07/kicking-off-the-summer-of-love/) – David Feb 05 '14 at 15:37
  • I don't know if and when it changed, but `ToString()` does not throw an exception (anymore): https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1.tostring?view=net-5.0 – Kai Hartmann Feb 26 '21 at 08:46

6 Answers6

36

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;
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • 1
    And how does `Convert` handle `null`? Does it return "null" as OP asked? – Yola Apr 09 '20 at 13:30
  • 1
    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. – Sachin Apr 11 '20 at 08:43
  • 4
    to be clearer,`Convert.ToString(a)` returns `""` not `null` – Guerrilla Dec 07 '21 at 22:34
4

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

string str = a.HasValue ? a.Value.ToString() : "Null";
Roland Bär
  • 1,720
  • 3
  • 22
  • 33
4

The shortest answer is:

int? a = null;
string aString = a?.ToString() ?? "null";
Amir
  • 1,214
  • 7
  • 10
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.

Liath
  • 9,913
  • 9
  • 51
  • 81
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"
DavidN
  • 5,117
  • 2
  • 20
  • 15
0
if(a.HasValue())
{
   return a.Value().ToString();
}
return string.Empty;
Vijay Vj
  • 347
  • 3
  • 15