Introduction
Ever encountered a situation where you had to use numerous parameters in String.Format
? If yes, then you must have really felt helpless when you wanted to move one parameter from one position to another position, and you really had to make sure that you pass the parameters in correct order.
Here is a cool little code snippet that might be helpful in this scenario.
Using the Code
Simply call FormatWithObject
on string
with your input parameters. You don't even have to remember the position of parameters. Let the function do the substitution at the right places like this:
UserInformation user = new UserInformation {
FirstName = "Joe",
LastName = "Doe",
Address1 = "Joe's House",
City = "San Jose",
Zipcode = "94101",
Email = "joe@doe.com",
PhoneNumber = "408000000"
};
var userInfoXml = @"<userinfo>
<firstname>{FirstName}</firstname>
<lastname>{LastName}</lastname>
<email>{Email}</email>
<phone>{PhoneNumber}</phone>
</userinfo>";
Console.WriteLine(userInfoXml.FormatWithObject(user));
Output
<userinfo>
<firstname>Joe</firstname>
<lastname>Doe</lastname>
<email>joe@doe.com</email>
<phone>408000000</phone>
</userinfo>
You can also use the function by passing Anonymous objects:
userInfoXml.FormatWithObject(new {
FirstName = "David",
LastName = "Luck",
Email = "davl@noemail.com",
PhoneNumber = "51000000"
})
Implementation
I use Reflection to enumerate the Object
properties and substitute the string
patterns:
public static string FormatWithObject(this string str, object o)
{
if (o == null) return str;
var outstr = str;
try {
var propertyNamesAndValues = o.GetType()
.GetProperties()
.Where(pi => pi.GetGetMethod() != null)
.Select(pi => new {
pi.Name,
Value = pi.GetGetMethod().Invoke(o, null)
});
propertyNamesAndValues
.ToList()
.ForEach(p => outstr = outstr.Replace("{" + p.Name + "}",
p.Value != null ? p.Value.ToString() : String.Empty));
} catch { }
return outstr;
}