Prash's Blog

Extension Methods : What When How September 28, 2009

Filed under: C# — prazjain @ 1:24 am
Tags: ,

What are Extension Methods

Interfaces have allowed us to attach only declaration of methods with them.
Extension methods provide a way to add behavior to an interface. This makes it more interesting as your interface definition and the implementing class can remain constant, but the new capabilities can be added to the interface (through extension methods).

When to use Extension methods

A general rule of thumb that goes while determining which methods should be part of interface and which ones should be extension methods :

Any methods that is part of generic implementation should be part of interface, whereas any specific implementation of that method should be an extension method.

Example:
Suppose there is a holiday planning service out there, then using extension how could it be designed :


public interface IHolidayPlanner
{
IList<Holiday> GetHolidays(int minPrice, int maxPrice, int duration);
}

public class HolidayPlanner : IHolidayPlanner
{
IList<Holiday> GetHolidays(int minPrice, int maxPrice, int duration)
{
return null // get the logic working here
}
}

// Now we could define extension methods around the generic implementation of IHolidayPlanner interface, for example searching for budget holidays and luxury holidays

public static class HolidayPlannerEx
{
public static IList<Holiday> GetBudgetHolidays<T>(this T planner,int duration) where T: IHolidayPlanner<T>
{
return planner.GetHolidays(0,1000,duration);
}

public static IList<Holiday> GetLuxuryHolidays<T>(this T planner,int duration) where T: IHolidayPlanner<T>
{
return planner.GetHolidays(1001,100000,duration);
}
}

In this way any specific implementation that could be built upon a generic implementation of a method in the interface could be declared as an extension method.

This example might not be the best way to design a holiday planning app, but I hope it get the message across about how Extension methods can be used.

Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s