Question
Calling ToString with own IFormatProvider doesn't work
This is about IFormattable
and IFormatProvider
. For sure one can achieve a reversed string representation of value 123 otherwise...
Every C# base data type implements the IFormattable
interface. So such a data type provides the method
public string ToString(string format, IFormatProvider formatProvider);
which allows according to the Microsoft documentation both:
You can also define your own format strings to support formatting of your application-defined types.
In addition, you can define your own custom format providers to supply culture-specific, profession-specific, or industry-specific information used in formatting.
From that is should be possible to write:
// Shall produce "321"
string s = 123.ToString("Z", ReverseFormatProvider);
where "Z" is my own format string and ReverseFormatProvider is my own (custom) format providers.
I followed the ICustomFormatter
interface example https://learn.microsoft.com/en-us/dotnet/api/system.icustomformatter?view=net-8.0.
But it uses only String.Format
and not ToString directly as Microsoft documentation says for ToString:
You can call the method directly. It is also called automatically by the Convert.ToString(Object) and Convert.ToString(Object, IFormatProvider) methods, and by methods that use the composite formatting feature in the .NET Framework, such as String.Format(String, Object[]), ...
In my ReverseFormatProvider GetFormat
always receives NumberFormatInfo
as formatType.
And as a consequence ToString("Z", new ReverseFormatProvider())
throws a System.FormatException
(unknown format string).
How do I manage to "attach" custom formatting to base data types by means of IFormatProvider?