Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

Custom String FormatWith using Reflection

4.00/5 (2 votes)
5 Jul 2012CPOL 12K   33  
Custom String FormatWith using Reflection

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:

C#
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));
XML
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:

C#
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:

C#
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;
 }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)