advanced web statistics

Generic'ish ToString Method Using Reflection

5/1/2008 1:07:53 AM

This is probably a late pass but I will post it nonetheless.  I created a Generic Helper class earlier this week and created a nifty ToString() method.  ToString overrides are nothing new but I've never posted about it and I love Reflection so it only makes sense.

Keep in mind this wouldn't work for properties that are of other objects (which could work if they had ToString overrides*), collections, etc..  I'm working on that though 8^)

public new string ToString()
{
   StringBuilder s = new StringBuilder();

   foreach (PropertyInfo p in typeof(T).GetType().GetProperties())
      s.AppendFormat("{0}: {1}<br />", p.Name, p.GetValue(this, null));

   return s.ToString();
}

Please note that I really wanted to post the variable "s" as "stringBuilder" and the variable "p" as "property" but refactored in my sandbox project for the sole purpose of posting.  I have CTRL+Z'ed since.

Call me crazy, but I like descriptive variable names.  The only time I'll use a 1 character variable name is in a for loop. We'll save those idiosyncracies for another day though.

If you want to implement this in a non-Generic class just remove the typeof(T). and you should be good to go.  Again, this is really high-level but works.

Easy.

* If you're other objects have ToString() methods you could just append .ToString() to the p.GetValue(this, null) line.

C#

kick it on DotNetKicks.com

Comments


Nice. It`s weird that that`s not the default behavior of ToString, as opposed to this.GetType().ToString() which I`m not sure I`ve ever needed to use. It`d be nice to go both directions, ToString() gives you the values in your instance, static T FromString(s) or whatever creates a new instance from the string you created in ToString(). eh?

Damn you session!
http://panteravb.com/imageviewer/image.ashx?id=40

Posted by: Chris | 5/1/2008 6:58:38 AM

Leave a Comment

   

  Enter the text to proceed!