Formatted object properties with ToString() method

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Hans-Jürgen Philippi

    Formatted object properties with ToString() method

    Hi group,

    let's say I have a 'Person' class with properties like 'FirstName',
    'LastName', 'Birthday' and so on. Now I overload the 'Person' ToString()
    method with an implementation ToString(string PlaceholderStri ng) of the
    following purpose:

    When someone calls ToString("{Last Name}, {FirstName}") on a given Person
    instance, the expected result is e.g. "Doe, John" for this object, that is:
    Any {property placeholder} is replaced by the actual instance value.
    Furthermore, the ToString(string PlaceholderStri ng) implementation is
    intended to work with arbitrary properties on any class, without knowing the
    members before.

    I've achieved this with reflection: When ToString(string PlaceholderStri ng)
    is called, I loop over the type members to fetch the currently available
    member/value pairs. In the same run, I do simple StringBuilder replacements
    of requested {property placeholder} values within the user given
    PlaceholderStri ng and finally hand the replacement result out.

    The whole thing works fine, I'm just asking myself: Is there a
    better/faster/more efficient way to do this? Or did I reinvent the wheel and
    there is an unknown .NET method with exactly the same function already?

    Any hint is greatly appreciated.

    Best regards,
    Hans


  • Ignacio Machin ( .NET/ C# MVP )

    #2
    Re: Formatted object properties with ToString() method

    The whole thing works fine,
    have you tried how expensive this is in a loop? like when doing
    databinding? Reflection in general is an expensive proposition that
    should be used with care.
    I'm just asking myself: Is there a
    better/faster/more efficient way to do this?
    not with those requirements,

    Of course it should be trivial (only a few more keystrokes) to call
    String.Format(" {0}, {1}") , FirstName, LastName)
    >Or did I reinvent the wheel and
    there is an unknown .NET method with exactly the same function already?
    only the above mentioned String.Format and frankly I do not see the
    need of another option

    what is superior in your method than using String.Format?

    Comment

    • Ignacio Machin ( .NET/ C# MVP )

      #3
      Re: Formatted object properties with ToString() method

      >
      what is superior in your method than using String.Format?
      I'm going to answer that myself :)

      The only advantage is that you can get that string from an external
      source (like a DB or a config file)

      Comment

      • Marc Gravell

        #4
        Re: Formatted object properties with ToString() method

        Reflection in general is an expensive proposition that
        should be used with care.
        There are ways around this performance hit in the general case...

        In this /specific/ case, I suspect the formatting etc will eat a
        comparable amount of CPU, so I won't bother posting the details - but it
        can be done ;-p More for things like bulk export/import...

        Marc

        Comment

        • Hans-Jürgen Philippi

          #5
          Re: Formatted object properties with ToString() method

          You name it - this is exactly one of our use cases where we'd have external,
          user created XML/HTML templates with content like "<div>Hello {Salutation}
          {LastName}, ...</div>"!
          I want to send them through the mentioned ToString() overload without caring
          about the actual members of the target class.

          Yes, I know that reflection is expensive. Therefore I wondered if there may
          be an optimized way to get this kind of instance self-information for my
          purpose.

          Regards,
          Hans


          "Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin @gmail.comschri eb im
          Newsbeitrag
          news:323f4dfc-5891-45a3-8c0e-79edfcadf6dc@w1 g2000prd.google groups.com...

          >what is superior in your method than using String.Format?
          >
          I'm going to answer that myself :)
          >
          The only advantage is that you can get that string from an external
          source (like a DB or a config file)

          Comment

          • Mihai N.

            #6
            Re: Formatted object properties with ToString() method

            I'm going to answer that myself :)
            >
            The only advantage is that you can get that string from an external
            source (like a DB or a config file)
            Another one: localization.
            When a translator gets "To {0} {1}" he has no clue what the heck this is all
            about. "To {firstName} {lastName}" is self-explanatory.


            --
            Mihai Nita [Microsoft MVP, Visual C++]
            Best internationalization practices, solving internationalization problems.

            ------------------------------------------
            Replace _year_ with _ to get the real email

            Comment

            • =?ISO-8859-1?Q?G=F6ran_Andersson?=

              #7
              Re: Formatted object properties with ToString() method

              Hans-Jürgen Philippi wrote:
              Hi group,
              >
              let's say I have a 'Person' class with properties like 'FirstName',
              'LastName', 'Birthday' and so on. Now I overload the 'Person' ToString()
              method with an implementation ToString(string PlaceholderStri ng) of the
              following purpose:
              >
              When someone calls ToString("{Last Name}, {FirstName}") on a given Person
              instance, the expected result is e.g. "Doe, John" for this object, that is:
              Any {property placeholder} is replaced by the actual instance value.
              Furthermore, the ToString(string PlaceholderStri ng) implementation is
              intended to work with arbitrary properties on any class, without knowing the
              members before.
              >
              I've achieved this with reflection: When ToString(string PlaceholderStri ng)
              is called, I loop over the type members to fetch the currently available
              member/value pairs. In the same run, I do simple StringBuilder replacements
              of requested {property placeholder} values within the user given
              PlaceholderStri ng and finally hand the replacement result out.
              >
              The whole thing works fine, I'm just asking myself: Is there a
              better/faster/more efficient way to do this? Or did I reinvent the wheel and
              there is an unknown .NET method with exactly the same function already?
              >
              Any hint is greatly appreciated.
              >
              Best regards,
              Hans
              >
              How about this:

              string[] props = new string[] { "FirstName" , "LastName", "Birthday" };
              string format = Regex.Replace(P laceHolderStrin g, @"\{(\w+)\}" ,
              delegate(Match m) { for (int i = 0; i < props.Length; i++) if
              (m.Groups[1].Value == props[i]) return "{" + i.ToString() + "}"; return
              m.Value; });
              return string.Format(f ormat, FirstName, LastName, Birthday);

              Just add the names of the properties in the array and in the Format call.

              --
              Göran Andersson
              _____
              Göran Anderssons privata hemsida.

              Comment

              • Hans-Jürgen Philippi

                #8
                Re: Formatted object properties with ToString() method

                Hi Göran,

                the way you use a regular expression to derive a format string is nice. But
                doing it like this, you need to know the class properties at design time and
                have to maintain a lookup array as well as a custom fitting String.Format()
                method by hand - where I wanted an approach to have ToString(string
                PlaceholderStri ng) generally working even in derived classes with completely
                new, unforeseen members!
                Maybe I mix my implementation with your code to create the props and
                String.Format() args arrays dynamically via reflection and benefit from the
                cool Regex appeal. ;-)

                Well, it appears like reflection is the tradeoff for the flexibility I need
                and there will hardly be a much more efficient (=faster, reliable, easy on
                resources *and* easy to maintain) way to do this.

                Thanks for your input,
                Hans


                "Göran Andersson" <guffa@guffa.co m>:
                >
                How about this:
                >
                string[] props = new string[] { "FirstName" , "LastName", "Birthday" };
                string format = Regex.Replace(P laceHolderStrin g, @"\{(\w+)\}" ,
                delegate(Match m) { for (int i = 0; i < props.Length; i++) if
                (m.Groups[1].Value == props[i]) return "{" + i.ToString() + "}"; return
                m.Value; });
                return string.Format(f ormat, FirstName, LastName, Birthday);
                >
                Just add the names of the properties in the array and in the Format call.


                Comment

                • Marc Gravell

                  #9
                  Re: Formatted object properties with ToString() method

                  and there will hardly be a much more efficient (=faster, reliable, easy on
                  resources *and* easy to maintain) way to do this.
                  Efficiency is tricky to define ;-p

                  For example, HyperDescriptor is significantly quicker at execution
                  (especially if you re-use the PropertyDescrip torCollection), but has
                  to generate a dynamic assembly on the fly, so bigger footprint (not by
                  much). Identical from a maintenance perspective.


                  [this is what I hinted at previously, but didn't post...]

                  Marc

                  Comment

                  • Hans-Jürgen Philippi

                    #10
                    Re: Formatted object properties with ToString() method

                    Hi Marc,
                    Efficiency is tricky to define ;-p
                    Yep, definitely true. :-)

                    For example, HyperDescriptor is significantly quicker at execution
                    (especially if you re-use the PropertyDescrip torCollection), but has
                    to generate a dynamic assembly on the fly, so bigger footprint (not by
                    much). Identical from a maintenance perspective.
                    >

                    [this is what I hinted at previously, but didn't post...]
                    Thanks for pointing me to this, I didn't know it before and it looks pretty
                    interesting. Don't be too modest, doing good things and not speaking about
                    it! ;-)


                    Greetings,
                    Hans


                    Comment

                    Working...