This is a very fun method. I wrote it for a project where I had non-programmers who wanted to be able to read my code. I tend to use StringBuilder.AppendFormat() and String.Format() a lot! I found that writing a method that makes string formatting a little more obvious to my non-programmer code reviewers helped out a bit. So here’s an example:
This method allows me to put in the name of properties as opposed to indexes of an array. It’s very helpful for simple String formatting. You do lose all of the integer and padding customizations with the original method but gain a large amount of readability. To pull this off, I used simple reflection and a regex.
public static String ToObjFmtString(this Object obj, string format)
{
return Regex.Replace
(
format,
@"\{(.*?)\}",
delegate(Match m)
{
return obj.GetType().GetProperty(m.Groups[1].ToString())
.GetValue(obj, null).ToString();
}
);
}