How can I call ToString()
on an object and make it use the invariant culture? There are overloads for ToString()
on objects that implement IConvertible
(like bool, int, float..), but what if the object in question is not IConvertible
?
You specify the invariant culture by name by using an empty string ("") in the call to a CultureInfo instantiation method. ... Unlike culture-sensitive data, which is subject to change by user customization or by updates to the .
The InvariantCulture property can be used to persist data in a culture-independent format. This provides a known format that does not change and that can be used to serialize and deserialize data across cultures.
The System.Convert
class has a static ToString
overload that takes an object
.
Convert.ToString(obj, CultureInfo.InvariantCulture);
Based on my benchmarks, this is roughly twice as fast as string.Format(CultureInfo.InvariantCulture, "{0}", value)
and, more importantly, it looks cleaner. However, if you are building a string already, I'd recommend FormattableString.Invariant.
FormattableString.Invariant($"Object value: {obj}")
I think IFormattable
is the relevant interface. It has a ToString
method that lets you specify the format provider, which can be a culture.
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