Scott Hanselman

RELEASE: FormattableObject an Aggregating reflection-based ToString() implementation

January 31, '05 Comments [3] Posted in ASP.NET | Internationalization | CodeRush
Sponsored By

Well, here you go, it's my implementation of a FormattableObject that I mentioned earlier. Take a look at the comments, Mark Miller had some great ideas, the best of which being a CodeRush plugin that handles the static analysis at design time and makes it harder to mess up these strings.

You can do this:

[Test]

public void MakePersonFormattedStringWithFormat()

{

    Person p = new Person();

    string foo = p.ToString("{BirthDate:D} My name is {FirstName} {LastName} and I'm cool.");

    Assert.AreEqual("Tuesday, January 22, 1974 My name is Scott Hanselman and I'm cool.", foo);

}

or

[Test]

public void MakePersonFormattedStringWithFormatAndChineseCulture()

{

    Person p = new Person();

    string foo = p.ToString("{BirthDate:D} My name is {FirstName} {LastName} and I'm cool.",new System.Globalization.CultureInfo("zh-cn"));

    Assert.AreEqual("1974?1?22? My name is Scott Hanselman and I'm cool.", foo);

}

You can either:

  • Derive your objects from FormattableObject and you get these ToString implementations for free

or

  • Implement a few ToString's and IFormattable yourself and delegate over to the static implementations in FormattableObject:

 
public string ToString(string format, System.IFormatProvider formatProvider)

{

    return Corillian.Voyager.Common.ObjectFormatString.ToString(this,format,formatProvider);

}

 

public string ToString(string format)

{

    return this.ToString(format,null);

}

Here you go, enjoy.  If you don't, screw you.  If you do, I take full credit.

FormattableObject 0.5 (11kb)

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.