简体   繁体   中英

ToString() with nullable data type

I need a nullable int and format it like in example, when value is not null. ToString() does not work with nulls. How to handle this best?

int? i = 5555;

string p = i.ToString("#,##0");
Console.WriteLine(p);

If you are using C#6 or later you could use the safe navigation operator:

string p = i?.ToString("#,##0");

Else you can use a conditional expression:

string p = i.HasValue ? i.Value.ToString("#,##0") : null;

Just check for null.

int? i = 5555;
string p;
if (i.HasValue)
     p = i.Value.ToString("#,##0");
else
     p = string.Empty;

Console.WriteLine(p);

Instance functions are not the way to go. If there is no instance (null), then there is nothing to call the instance function on. However there is an answer already part of Object in the form of the compare functions :

a.Equals(b) would fail if a is null. Wich is why there is the static function Object.Equals(a, b). Since a is given as argument, it can be checked on null. Just before the function calls a.Equals(b).

The other way is to check for null before printing. Because that can be verbose to write, the C# developers added the Null-conditional and null-coalesc operators. If you can use them depends on wich version of C# your Compiler speaks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM