culture invariant object ToString()
Asked Answered
A

2

35

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?

Alikee answered 17/9, 2011 at 21:23 Comment(0)
V
26

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

Vocoid answered 17/9, 2011 at 21:36 Comment(3)
Since a culture is a format provider, you can use it with String.Format(CultureInfo.InvariantCulture, "{0}", value)Pentup
Please use string instead of String as recommended.Gschu
@nitzel: C# isn't the only language in the .NET Framework.Sequential
P
53

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}")
Pirbhai answered 18/1, 2019 at 21:50 Comment(3)
"and looks cleaner" not if you began with a string interpolation with multiple items to be escaped. With string.Format, it does them all at once.Rhesus
@jeromej: That's a good point, although if you're using string interpolation I'd recommend FormattableString.Invariant for improved readability. I updated my answer accordingly.Pirbhai
Convert.ToString(Object, IFormatProvider) overload internally makes use of casts to IConvertible and IFormattable and uses instance method Object.Tostring() as a fallback. The implementation if identical in .NET Framework 4.8 and current .NET. referencesource.microsoft.com/#mscorlib/system/… github.com/dotnet/runtime/blob/…Puccini
V
26

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

Vocoid answered 17/9, 2011 at 21:36 Comment(3)
Since a culture is a format provider, you can use it with String.Format(CultureInfo.InvariantCulture, "{0}", value)Pentup
Please use string instead of String as recommended.Gschu
@nitzel: C# isn't the only language in the .NET Framework.Sequential

© 2022 - 2024 — McMap. All rights reserved.