Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

culture invariant object ToString()

Tags:

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?

like image 559
codymanix Avatar asked Sep 17 '11 21:09

codymanix


People also ask

How to set invariant culture in c#?

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 .

What does invariant culture do?

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.


2 Answers

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}") 
like image 175
StriplingWarrior Avatar answered Sep 16 '22 17:09

StriplingWarrior


I think IFormattable is the relevant interface. It has a ToString method that lets you specify the format provider, which can be a culture.

like image 23
CodesInChaos Avatar answered Sep 19 '22 17:09

CodesInChaos