A well-used string extension method
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.
Leave a Reply