Chris Canal

A Scottish .NET Developer

  Home  |   Contact  |   Syndication    |   Login
  23 Posts | 0 Stories | 19 Comments | 0 Trackbacks

News

Twitter












Archives

Post Categories

I've being considering using reflection within a classes .ToString() method, something along the lines of this:

    public override string ToString()
        {
            StringBuilder toString = new StringBuilder();
            PropertyInfo[] props = GetType().GetProperties();

            foreach (PropertyInfo prop in props)
            {
                toString.AppendFormat("{0} : {1} || ", prop.Name, prop.GetValue(this, null));
            }

            return toString.ToString();
        }

Is this smelly code?
posted on Monday, January 07, 2008 3:48 AM

Feedback

# re: Using Reflection in .ToString()... 1/7/2008 1:57 PM Jason Bock
To me, it's smelly.

ToString() should be simple and fast: it just prints out a very short description of the object. This isn't simple (it uses Reflection) and it isn't fast (it uses Reflection :) ). Plus, you KNOW what fields you want to publish in the object.

I'd consider two changes:

1) Make ToString() simple, and report only the pertinent information.
2) Overload ToString() to pass in a format value. If you get a known format value, you can go down the "blast-out-every-property-known" approach.
3) Consider delegating this work to a DynamicMethod. This will be quicker.

Regards,
Jason
http://www.jasonbock.net

# re: Using Reflection in .ToString()... 1/7/2008 3:23 PM Chris Eargle
I agree with Jason; the ToString method should be light and return a short description.

# re: Using Reflection in .ToString()... 1/10/2008 7:27 PM Jason Bock
BTW I posted how you'd do this with a DynamicMethod:

http://www.jasonbock.net/JB/Default.aspx?blog=entry.ddbdccf6002747149ee464ced6577764

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 1 and 1 and type the answer here: