Dynamic String Formatting == Dynamic Assemblies ? RRS feed

  • Question

  • My users need to be able to specify their own formatting preferences for certain strings in my system for display on forms, reports, etc.

    Here's an extremely simplified example of what I'm talking about.

    In the app Settings or the database or wherever, they specify a format string: "%lastName% can be reaced at %mainPhone% or %email%" to control the output of this class:

    class Person
    string nameFirst;
    string nameLast;
    string eMail;
    List<Phone> phones;
    I'm wondering how to best produce the final string at runtime in a reasonably efficient manor. It's doubtful there will be more than a few hundred of these items at a time (less than a dozen most likely) and this string will be produced for tooltips, columns in grids, reports, etc. Still - while I don't have to worry about this logic being executed a 1,000 times a second - I don't want a slow UI.

    It seems to me this is a good use for codeDOM and generating a dynamic method. When the app is loaded, it reads the configuration string and generates a method that looks

    string DisplayAs()
    // i.e. based on the configuration string originally specified as "%lastName% can be reaced at %mainPhone% or %email%"
    string fmt = "{0} can be reached at {1} or {2}";

    string[] args = { nameLast, SomeMethodThatKnowsHowToDetermin_MAIN_PhoneFromList(), eMail };

    return string.Format ( fmt, args );
    I've never used the codeDOM but I think I can manage something like this. But is this overkill or maybe there's a better way?

    I could take a brute force approach and loop through whatever format string the user supplies doing string substitutions based on my list of 'keywords' (i.e. %mainPhone%) but there could easily be a dozen or so of those keywords. Doing that in every ToString() override just seems painfully inefficient to me - but maybe not to the extent I should worry about it.

    I looked at IFormatting but it's not applicable in this context.

    Dan Holt
    Thursday, July 3, 2008 2:01 PM


All replies

  • CodeDom will not give you faster code. A very quick approach to format a given templat can be found at my blog:


    The trick is to have a good understanding how StringBuilder works and where it is efficient and not so efficient to use. Some string operations do differ quite a lot:


      Alois Kraus
    • Marked as answer by holtd Thursday, July 3, 2008 3:40 PM
    Thursday, July 3, 2008 2:15 PM
  • Thanks, Alois, that was exactly what I needed. Great work, BTW.

    I haven't had time to study all of this and it will be another couple weeks before I will be able to try it.

    Is it OK to use this code? The context makes it look like it's part of a larger product.

    Thanks again,
    Thursday, July 3, 2008 3:47 PM
  • Sure you can use the code. It is free.

       Alois Kraus

    Thursday, July 3, 2008 9:04 PM