Wednesday, March 9, 2011

Dynamic Sugar # Library's Format Method

Dynamic Sugar # Library provides methods and functions inspired by the dynamic/functional language Python to write more readable code in C#.
My favorite method is the static member Format, which also can be turned into an extension method to be assigned to any class.

It first started with this Python code:
class Person(object):

  def __init__(self, name, age):
    self.name = name
    self.age  = age

  def Format(self, format):
      return format.format(**self.__dict__)

p = Person("Fred", 45)
print p.Format("name={name}, age={age}")

With reflection and extension methods, I obtained this code, which I like.
You can define how to format the value of the properties (see the property BirthDay below).
And the method know hows to output nicely List<T>, Dictionary<K,V> and Array.

Person p = new Person() {

    LastName        = "TORRES"  ,
    FirstName       = "Frederic",
    BirthDay        = new DateTime(1964,12, 11),
    DrivingLicenses = DS.List("Car", "Moto Bike")
};
Console.WriteLine( // Call 4 properties in the format
    p.Format("FullName:'{LastName},{FirstName}', BirthDay:{BirthDay:MM/dd/yyyy}, DrivingLicenses:{DrivingLicenses}")
);

//

Here is the output

FullName:'TORRES,Frederic', BirthDay:12/11/1964, DrivingLicenses:["Car", "Moto Bike"]

You can also format based on a dictionary, like this
var format = "LastName:{LastName}, FirstName:{FirstName}, Age:{Age:000}";

var Values = new Dictionary<string, object>() {

    { "LastName" , "TORRES"   },
    { "FirstName", "Frederic" },
    { "Age"      , 45         }
};
Console.WriteLine(ExtendedFormat.Format(format, Values));


And while I was at it, I added support for the ExpandoObject, which make this kind of simple formatting more concise

var format    = "LastName:{LastName}, FirstName:{FirstName}, Age:{Age:000}";
            
dynamic bag   = new ExpandoObject();
bag.LastName  = "TORRES";
bag.FirstName = "Frederic";
bag.Age       = 45;
            
Console.WriteLine(ExtendedFormat.Format(format, bag));

//

No comments:

Post a Comment