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 toToString(null, null)
andToString("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()
If you check the source code, you will notice that
ToString()
callswhile
String ToString(String format, IFormatProvider provider)
callsSo the
format
is actuallynull
, not"G"
. It doesn't make a difference though, as"G"
andnull
should be the same.NumberFormatInfo.GetInstance(null)
returnsNumberFormatInfo.CurrentInfo
, soInt32.ToString()
is equivalent toInt32.ToString("G", null)
orInt32.ToString(null, null)
.You can double check it with IFormattable.ToString documentation to see that
null
s indeed indicate default values for both parameters.