Confused
Confused

Reputation: 879

With C# under what circumstances do I need to supply a CultureInfo IFormatProvider when using ToString() on a String or Char?

With C# under what circumstances do I need to supply a CultureInfo IFormatProvider when using ToString() on a String or Char?

I get it with number or date conversion, e.g.

(-10000.4).ToString(provider: new System.Globalization.CultureInfo("es-ES"));
(-10000.4).ToString(provider: new System.Globalization.CultureInfo("en-US"));

DateTime.Now.ToString(provider: new System.Globalization.CultureInfo("es-ES"));
DateTime.Now.ToString(provider: new System.Globalization.CultureInfo("en-US"));

giving:

-10000,4
-10000.4
01/05/2018 22:49:09
5/1/2018 10:49:09 PM

but what about the following:

"Some string".ToString(provider: new System.Globalization.CultureInfo("es-ES"));
"Some string".ToString(provider: new System.Globalization.CultureInfo("en-US"));

What strings could I possibly use that would be affected by culture?

Same for char.

Upvotes: 2

Views: 193

Answers (1)

adjan
adjan

Reputation: 13652

Under no circumstance, since it does not do anything. As the MSDN documentation for String.ToString(IFormatProvider provider) states:

provider is reserved, and does not currently participate in this operation.

Because this method simply returns the current string unchanged, there is no need to call it directly.

The same applies to Char.ToString(IFormatProvider provider).


The reason why String and Char have this apparently useless method is that it is needed to implement the IConvertible interface, that e.g. allows conversion from string to int, int to string etc.

Upvotes: 7

Related Questions