Tech Off Post

Single Post Permalink

View Thread: C# Sting converstion
  • User profile image

    stevo_ said:
    the_corona said:

    It works because the formatting system has an interface IFormattable which any type can implement, it specifies the type then must have a method ToString(string format, IFormatProvider formatProvider).


    The string 'format' would be the part after the colon in String.Format, and of course you can call it directly as in your example of myDate.ToString("ddMMYYYY") (which is actually an overload that doesn't require you to specify the format provider).


    The String.Format method works by scanning for the curly brace syntax, if it detects the colon then the following characters until the closing brace are considered the format, if the argument in question is IFormattable then it passes in the format with a format provider it either discovered itself or you provided in the Format call.


    If the type isn't formattable it simply calls ToString on it to get a string value.


    So if you want your type to have its own custom formatting like:


    string.Format("{0:omgbbq}", instanceofmytype).


    You simply need to implement IFormattable on your type and do the work to process what the format ('omgbbq' in this case) should mean.


    The format providers role is to allow 'outsiders' to specify their own formatter (ICustomFormatter) (albiet imo somewhat convolutedly).


    The concept when implementing is.. is a format provider was given, try and get a custom formatter from it, if you get one use that.. otherwise use your own built in formatting.

    Awesome, thnx for the clear explanation. Learned something valuable today!