Scott Hanselman

Is this a good idea? Has it been done? Should it? An Aggregating ToString() implementation...

January 28, '05 Comments [14] Posted in ASP.NET | NUnit
Sponsored By

Travis and I were kicking around this idea. It's either already been done and it's a great idea, it's a good idea and no one has bothered, or it's stupid because _______.

We use a lot of "Domain Objects" like say, "public class Person." Why not have a "aggregated" ToString override like this:

Person p = new Person("Scott","Hanselman",new DateTime(1974,1,22);
//blah blah blah
string foo = p.ToString("My name is {FirstName} {LastName} and my birthday is {Birthdate:MM/dd/yyyy}");

Is this stupid? Would it gain you anything over:

string foo = String.Format("My name is {0} {1} and my birthday is {2:MM/dd/yyyy}",p.FirstName,p.LastName,p.BirthDate);

I've got it half done, but I wanted to know your thoughts before I finish it.

My thinking is that, even though it'd be slow (Reflection) it's useful for these reasons:

  • Quick Testing - Seems convenient to me, useful for NUnit.
  • Ultra-Late Bound - Ya, I know I'm Mr. So-Early-Bound-I-Generate-Everything but sometimes you just don't know until late, which leads me to:
  • Externalization of Complex Formatted Strings - True, you're embedding knowledge of your properties in a string, but it'd allow you to add a different series of fields if another language required it. This would be an improvement over ordinal style ({0}, {1}) format strings, no? Perhaps a silly use case.
  • DataBinding - You can let an ASP.NET DataGrid just call ToString on an object and it'll "do the right thing" as opposed to doing a TemplateColumn or an OnItemDataBound callback.
  • It just calls down into the underlying object's ToString - It's basically using the aggregate ToString's format string to get Properties and Fields and call their respective ToString's using the embedded (after the colon) format string.

Am I smoking crack?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.