String.Format - how it works and how to implement custom formatted strings

With String.Format() you can format, for example, DateTime objects in many ways. Every time I search for the format I want, I need to search the Internet. Almost always, I find an example that I can use. For example:

 String.Format("{0:MM/dd/yyyy}", DateTime.Now); // "09/05/2012" 

But I don’t know how this works and which classes support these β€œmagic” extra lines.

So my questions are:

  • How does String.Format match additional MM/dd/yyyy with a string result?
  • Do all Microsoft objects support this feature?
    Is it registered somewhere?
  • Is it possible to do something like this:
    String.Format("{0:MyCustomFormat}", new MyOwnClass())
+74
string c # string-formatting
May 09 '12 at 8:20
source share
7 answers

String.Format corresponds to each of the tokens inside the string ( {0} , etc.) for the corresponding object: http://msdn.microsoft.com/en-us/library/system.string.format.aspx

Additionally, a format string is provided:

{ index[,alignment][ : formatString] }

If formatString provided, the corresponding object must implement IFormattable and, in particular, the ToString method, which accepts formatString and returns the corresponding formatted string: http://msdn.microsoft.com/en-us/library/system.iformattable.tostring.aspx

IFormatProvider can also be used, which can be used to capture the basic formatting standards / default values, etc. Examples here and here .

So, the answers to your questions are in order:

  • It uses the IFormattable interface ToString() method for the DateTime object and passes a string of the format MM/dd/yyyy . This is an implementation that returns the correct string.

  • Any object that implements IFormattable supports this function. You can even write your own!

  • Yes, see above.

+77
May 9 '12 at 8:27
source share

From my point of view, you will need to implement IFormattable in your class to support this. Then there is the ToString method, which takes the parameters that you pass to 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()) 
+16
May 9 '12 at 8:26 AM
source share
  • Check the official MSDN docs, here is a complete list of DateTime format strings: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx . In fact, there are many "magic" lines.

  • As far as I know, not all types have "interesting" formatting, but all types support ToString() . If you need to format the built-in object, you can add an extension method for this, but usually formatting is provided anywhere you need it (or, to put it another way, I only have my own custom formatting for my own types).

  • Yes, you can write your own, and if you have data that can be formatted in different ways, you probably should write your own formatter by running IFormattable, look again at the documents here: http://msdn.microsoft.com/ en-us / library / system.iformattable.aspx . It's quite simple, you just check the provided lines and write your data based on them, there is no magic behind the scenes :-)

+4
May 09 '12 at 8:28
source share

Under the covers of String.Format does the following,

 IFormattable formattable = objectToFormat as IFormattable; if (formattable != null) { formattable.ToString(objectToFormat); } else { objectToFormat.ToString(); } 

For all questions,

  • How does String.Format match additional MM / dd / yyyy information with a string result?

    As stated above, it simply calls IFormattable.ToString (string format, IFormatProvider provider). A supplier is often what tells you what your system culture is. Often null, because people do not pass it String.Format (), as it was in your case.

  • Does all Microsoft objects support this feature? Is it documented anywhere?

    Everything that implements IFormattable does.

  • Is it possible to do something like this: String.Format("{0:MyCustomFormat}, new MyOwnClass())

    Essentially, if you want your own object to do something with the format, provided that you implement IFormattable .

There are a huge number of supporting classes and counters to ensure that format strings are very similar. More details here .

+3
May 9 '12 at 8:32
source share

Yes, it is possible - it can be fully customized. See this link for date and time formatting documentation.

If you have your own object, you should override the ToString() method and print everything that you think is appropriate. After that, you can use String.Format("{0:MyCustomFormat}", new MyOwnClass()) because it implicitly calls MyOwnClass.ToString()

0
May 9 '12 at 8:24
source share

Date documentation can be found here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

This should indicate exactly what all date formatting characters, such as MM, mean.

If you want to change the way string is displayed for a custom class, you can override the ToString method, for example:

 public class User { public string Name { get; set; } public int Age { get; set; } public override string ToString() { return this.Name + " is " + this.Age + " years old."; } } 

and then you can just do something like myUser.ToString() and get the result you specified.

0
May 09 '12 at 8:26
source share

And to answer your third question: this is not possible with this syntax, but you can provide instances of IFormatProvider and ICustomFormatter for a type that you have not created, or implement IFormattable inside your type (although that basically extends ToString ).

0
May 9 '12 at 8:29
source share



All Articles