Extension Methods
In the past, when you wanted to add additional methods to a class, you had to subclass the class and then add whatever methods you needed. In C# 3.0, you can just use the new extension methods feature to add a new method to an existing CLR type.
To see how extension methods work, consider the following example. Suppose you deal very frequently with the Point class and you want to be able to quickly find out the distance between two points. In this case, you might be better served by adding a new function called DistanceFromThisPointTo() to the Point class so it can return the distance between two Point objects. To do so, define a new static class and define the extension method (a static method) within it, like this:
public static class MethodsExtensions
{
public static double DistanceFromThisPointTo(
this Point PointA, Point PointB)
{
return Math.Sqrt(
Math.Pow((PointA.X - PointB.X), 2) +
Math.Pow((PointA.Y - PointB.Y), 2));
}
}
Here, the first parameter of the extension method is prefixed by the
Point, which indicates to the compiler that this extension method must be added to the
Point class. The rest of the parameter list consists of the signature of the extension method. To use the extension method, you can simply call it from a
Point object, like this:
Using MethodsExtensions;
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
Point ptA = new Point(3, 4);
Point ptB = new Point(5, 6);
Console.WriteLine(ptA.DistanceFromThisPointTo(ptB));
}
}