With String.Format() it is possible to format for example DateTime objects in many different ways. Every time I am looking for a desired format I need to search around on Internet. Almost always I find an example I can use. For example:
String.Format("{0:MM/dd/yyyy}", DateTime.Now); // "09/05/2012"
But I don't have any clue how it works and which classes support these 'magic' additional strings.
So my questions are:
- How does
String.Formatmap the additional informationMM/dd/yyyyto a string result? - Do all Microsoft objects support this feature?
Is this documented somewhere? - Is it possible to do something like this:
String.Format("{0:MyCustomFormat}", new MyOwnClass())
String.Format matches each of the tokens inside the string ({0} etc) against the corresponding object: http://msdn.microsoft.com/en-us/library/system.string.format.aspx
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: http://msdn.microsoft.com/en-us/library/system.iformattable.tostring.aspx
An IFormatProvider may also used which can be used to capture basic formatting standards/defaults etc. Examples here and here.
So the answers to your questions in order:
It uses the
IFormattableinterface'sToString()method on theDateTimeobject and passes that theMM/dd/yyyyformat string. It is that implementation which returns the correct string.Any object that implement
IFormattablesupports this feature. You can even write your own!Yes, see above.