I'm writing some string output formatting code for aggregated records (think CSV format output). I'm trying to write it so that it leverages the built-in string formatting capabilities of many types via the IFormattable.ToString(string, IFormatProvider)
interface, in addition to the simple object.ToString()
.
To reduce code duplication, it would be nice to be able to make some assumptions about the relationship between object.ToString()
and IFormattable.ToString(string, IFormatProvider)
.
For example, could it be relied upon to assume that ToString() == ToString(null, null)
? Is there a default culture or format provider that maintains that mapping? Or is there no necessary relationship between the two?
Based on the MSDN documentation and .NET source code you can assume that for built-in types ToString()
is equivalent to ToString(null, null)
and ToString("G", null)
.
There is some information about it in Formatting Types in the .NET Framework on MSDN.
For example according to that site Int32.ToString()
Calls
Int32.ToString("G", NumberFormatInfo.CurrentInfo)
to format theInt32
value for the current culture.
If you check the source code, you will notice that ToString()
calls
Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
while String ToString(String format, IFormatProvider provider)
calls
Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
So the format
is actually null
, not "G"
. It doesn't make a difference though, as "G"
and null
should be the same. NumberFormatInfo.GetInstance(null)
returns NumberFormatInfo.CurrentInfo
, so Int32.ToString()
is equivalent to Int32.ToString("G", null)
or Int32.ToString(null, null)
.
You can double check it with IFormattable.ToString documentation to see that null
s indeed indicate default values for both parameters.
Parameters
format
The format to use.
-or-
A null reference (Nothing in Visual Basic) to use the default format defined for the type of the IFormattable implementation.
formatProvider
The provider to use to format the value.
-or-
A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.