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
?
culture invariant object ToString()
Asked Answered
I think IFormattable
is the relevant interface. It has a ToString
method that lets you specify the format provider, which can be a culture.
Please use
string
instead of String
as recommended. –
Gschu @nitzel: C# isn't the only language in the .NET Framework. –
Sequential
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}")
"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
I think IFormattable
is the relevant interface. It has a ToString
method that lets you specify the format provider, which can be a culture.
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.
String.Format(CultureInfo.InvariantCulture, "{0}", value)
– Pentup