Sunday, January 16, 2011

Using expression trees to optimize your code

Hi,

A few days ago I wanted to use attributes to make my code easier. The problem was that It cost me in performance and I couldn’t afford it at this point of the code, so I decided to use expression to optimize my code.

Lets say we want to make a [DefaultValue] attribute that will set a default value for a property

  1: public class Person
  2:     {
  3:         [DefaultValue("Alon")]
  4:         public string Name { get; set; }
  5:         [DefaultValue("Nativ")]
  6:         public string LastName { get; set; }
  7:         [DefaultValue("http://blogs.microsoft.co.il/blogs/alon_nativ/")]
  8:         public string Blog { get; set; }
  9:
 10:         public override string ToString()
 11:         {
 12:             return string.Format("Name: {0}, LastName: {1}, Blog: {2}", Name, LastName, Blog);
 13:         }
 14:     }

Read more: .Net && Beyond