Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a nullable int to a string that will be safe for computers in different locales?

I'm converting a nullable integer to a string, and Resharper warns me to use InvariantCulture.

shipment.ShipmentID.ToString()

A quick Alt-Enter, Enter later, gives me this:

shipment.ShipmentID.ToString(CultureInfo.InvariantCulture)

Unfortunately, Resharper isn't satisfied, and suggests the same thing, which doesn't make sense to me.

shipment.ShipmentID.ToString(CultureInfo.InvariantCulture, 
                                CultureInfo.InvariantCulture)

ToString() on the nullable int won't build, giving me an error stating No overload method 'ToString' takes 1 arguments.

Non-nullable ints behave differently.

int requiredInt = 3;
// no Resharper or compiler warning
var stringFromRequiredInt = requiredInt.ToString(CultureInfo.InvariantCulture); 

What should I do to convert a nullable int to a string that will be safe for computers in different locales?

like image 595
Jon Crowell Avatar asked Apr 12 '12 16:04

Jon Crowell


2 Answers

Nullable<T> doesn't have a ToString() overload with arguments; ReSharper isn't quite handling the situation properly.

Since default(Nullable<int>).ToString() returns string.Empty, you can make ReSharper happy like this:

shipment.ShipmentID.HasValue 
        ? shipment.ShipmentID.Value.ToString(CultureInfo.InvariantCulture) : ""

Alternatively:

shipment.ShipmentID != null 
        ? ((int)shipment.ShipmentID).ToString(CultureInfo.InvariantCulture) : ""
like image 167
phoog Avatar answered Nov 09 '22 17:11

phoog


Check this link.

you should use the invariant culture only for processes that require culture-independent results, such as system services. In other cases, it produces results that might be linguistically incorrect or culturally inappropriate.

UPDATE: So one of the main purposes to use it might be e.g. 'if' statement comparison.

like image 42
Dave Avatar answered Nov 09 '22 17:11

Dave