String.Format – how it works and how to implement custom formatstrings

String.Format matches each of the tokens inside the string ({0} etc) against the corresponding object: https://learn.microsoft.com/en-us/dotnet/api/system.string.format#overloads

A format string is optionally provided:

{ index[,alignment][ : formatString] }

If formatString is provided, the corresponding object must implement IFormattable and specifically the ToString method that accepts formatString and returns the corresponding formatted string: https://learn.microsoft.com/en-us/dotnet/api/system.iformattable.tostring

An IFormatProvider may also be used to capture basic formatting standards/defaults etc. Examples here and here.

So the answers to your questions in order:

  1. It uses the IFormattable interface’s ToString() method on the DateTime object and passes that the MM/dd/yyyy format string. It is that implementation which returns the correct string.

  2. Any object that implement IFormattable supports this feature. You can even write your own!

  3. Yes, see above.

Leave a Comment