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

c#, int, locale, nullable, type-conversion

Solution

`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) : ""

Problem

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?

Original source