Custom String FormatWith using Reflection

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 = "",
        PhoneNumber = "408000000"

      var userInfoXml = @"<userinfo>


You can also use the function by passing Anonymous objects:

userInfoXml.FormatWithObject(new {
        FirstName = "David",
        LastName = "Luck",
        Email = "",
        PhoneNumber = "51000000"


We 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()
          .Where(pi => pi.GetGetMethod() != null)
          .Select(pi => new {
            Value = pi.GetGetMethod().Invoke(o, null)
          .ForEach(p => outstr = outstr.Replace("{" + p.Name + "}",
            p.Value != null ? p.Value.ToString() : String.Empty));
      } catch { }
      return outstr;

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s