Click here to Skip to main content
15,880,503 members
Articles / General Programming / String
Tip/Trick

Custom String FormatWith using Reflection

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
5 Jul 2012CPOL 11.7K   33   5   2
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)


Written By
Software Developer (Senior)
United States United States
I am currently working as a Senior Software Developer. My primary skills include .NET, WPF,MSSQL,and C++. I have also worked in ASP.NET, XML, XSL, JavaScript,and Web Automation.
I love to solve problems,and love to do programming. In my idle time i love to explore new technologies and domains.

Comments and Discussions

 
GeneralPretty cool Pin
Matt T Heffron6-Jul-12 12:23
professionalMatt T Heffron6-Jul-12 12:23 
GeneralRe: Pretty cool Pin
Sumit Chawla6-Jul-12 12:41
Sumit Chawla6-Jul-12 12:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.