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

Solution 1:

String.Format matches each of the tokens inside the string ({0} etc) against the corresponding object: https://docs.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://docs.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.

Solution 2:

From my understanding, you would need to implement IFormattable in your class to support this. That then has the method, ToString which takes the parameters you pass into String.Format.

Here is an example.

// Define other methods and classes here
public class Sample : IFormattable
{
     public string ToString(string format, IFormatProvider provider)
     {
         return String.Concat("Your custom format was ", format);
     }
}

String.Format("{0:MyCustomFormat}", new Sample())

Solution 3:

  1. Check the official MSDN docs, there is a full list of DateTime format strings here: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx. There are indeed quite a few "magical" strings.

  2. As far as I know not all types have "interesting" formatting, but all types support ToString(). If you needed to format a built in object you could add an extension method to do it, but usually formatting is provided in any place where it is needed (or to put it another way, I have only written custom formatters for my own types).

  3. Yes, you can write your own and if you have data that can be formatted in different ways you probably should write a custom formatter by implementing IFormattable, again see the docs here: http://msdn.microsoft.com/en-us/library/system.iformattable.aspx. It's fairly simple, you simply check the strings provided and write out your data based on these, there's no magic behind the scenes:-)