If only I were

Building Great Software

A well-used string extension method

leave a comment »

James-Newton King posted an interesting extension method called FormatWith() that you can call from any string literal or variable.

There are two useful aspects to this function.  1) You can format a string inline instead of wrapping your string with String.Format():

string Name = “Chris”;

“My name is {0}”.FormatWith(Name);

In my opinion, the less you have to nest items – String.Format(“…{0}”) – the easier it will be to read. Chaining items together could be abused, but over all it is simpler for the reader and writer.

2) It allows for named placeholders like this:

Person aPerson = new Person();

aPerson.FirstName = “Chris”;

aPerson.LastName = “Sutton”;

“My full name is {FirstName} {LastName}”.FormatWith(aPerson);

Check out James’ post to see his implementation, its surprisingly simple.

Much of what C# 3.0 brought us was simplified syntax and the potential for code that is easier to read and write (more fluent). This use of extension methods is more natural and expressive and will certainly make my coding cleaner.

Advertisements

Written by Chris Sutton

March 28, 2008 at 8:58 am

Posted in Technology

Tagged with , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: