Saturday, January 8, 2011

Extended the .NET string.format()

Introduction
Inspired by Python, I wanted to extend the .NET string.format() method so I can write the following C# code.

public  class  Person  {
 
     public  string    LastName;
     public  string    FirstName   { get ; set ; }
     public  int       Age         { get ; set ; }
     public  DateTime  BirthDay    { get ; set ; }
 }

static  void  Main(string [] args) {
 
     var  person = new Person () { LastName = "TORRES" , FirstName = "Frederic" , Age = 45, BirthDay = DateTime .Parse("1964-12-11" ) };
 
     Console.WriteLine(person.Format("{0} LastName:{LastName}, FirstName:{FirstName}" , DateTime .Now));
}



Without the extension method.

class  Program  {
 
     static  void  Main(string [] args) {
 
         var  person = new  Person () { LastName  = "TORRES" ,  FirstName = "Frederic" , Age = 45, BirthDay  = DateTime .Parse("1964-12-11" ) };
 
         Console.WriteLine(ExtendedFormat.Format(person, "LastName:{LastName}, FirstName:{FirstName}" ));
 
         // Combine extended and default mode 
         Console.WriteLine(ExtendedFormat.Format(person, "{0} LastName:{LastName}, FirstName:{FirstName}" , DateTime .Now));
     }
 }

The ExtendedFormat.Format() fall back on the string.Format() method and therefore it is 100% compatible. Basically The ExtendedFormat.Format() add the tag {property-name} to call a property or field of the instance passed.
I also added the ability to call a function with no parameter with the syntax{MyFunction()}.


Next Steps
I will look at different template class in Python. I sometime need a little bit more for than just the simple format.
I will add the source code to codeplex.com.

No comments:

Post a Comment