Tech Off Post

Single Post Permalink

View Thread: C# Sting converstion
  • User profile image

    the_corona said:
    Sven Groot said:

    ah, yes thats interesting, though I've never seen this before. I have to wonder though why you need to specify culturinvariant in that example given you very specifically ask for ddMMyyyy ?


    But come to think of it, Date.ToString I think also has an overload to do the formating the way you want, so even something like myDate.ToString("ddMMYYYY") - (I'm not sure of the exact syntax) - could get you a culture invariant string.


    Thinking about this more. does the {0:xx} in string.format end up as a string parameter to the first argument's ToString(string format)

    overload? So it ends up like

    string.format("{0:xx}", myDate) == string.format("{0}", myDate.ToString("xx"));

    Does this work in general or only with DateTime?



    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.