Feeds:
Posts
Comments

Posts Tagged ‘Extension Methods’

Have you ever wanted to add a method to an existing type without recompiling? Well in C# 3.0 you were given that ability with extension methods. On the MSDN it states that “extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.” I am going to give you a very simple example. Lets say you are creating a music management application and you have a class called Artist that looks like the following:

namespace MusicApp
{
     public class Artist
     {
          #region Properties

          public DateTime BirthDate { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }

          #endregion

          #region Constructor(s)

          public Artist(string lastName, string firstName, DateTime birthDate)
          {
               this.BirthDate = birthDate;
               this.LastName = lastName;
               this.FirstName = firstName;
          }

          #endregion
     }
}

As you can see the artist class has a birth date. What if we wanted to find the age of the artist? We could easily add a method to the class to do so, but lets use an extension method instead. We’ll be placing the code for our extension method inside a new public static class conveniently called ExtensionMethods. Here is the code:

static class ExtensionMethods
{
     public static int Age(this Artist artist)
     {
          DateTime now = DateTime.Now;
          int yearsPassed = DateTime.Now.Year - artist.BirthDate.Year;

          if (now.Month < artist.BirthDate.Month || (now.Month == artist.BirthDate.Month && now.Day < artist.BirthDate.Day))
          {
               yearsPassed--;
          }

          return yearsPassed;
     }
}

Please note that the first parameter to the extension method specifies the type the method operates on and is preceded by the this modifier. In order to use the new extension method we must import the namespace it was defined in. We are then able to determine an artist’s age like so. Enjoy!

Artist tomPetty = new Artist("Petty", "Tom", new System.DateTime(1950, 10, 20));
int age = tomPetty.Age();

Read Full Post »