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?
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) : ""
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With