Extension Method On C#

Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:

  1. Extension methods cannot be used to override existing methods
  2. An extension method with the same name and signature as an instance method will not be called
  3. The concept of extension methods cannot be applied to fields, properties or events
  4. Use extension methods sparingly....overuse can be a bad thing!
I give you the simplest example as illustration, consider we have Geometri class and it's method GetCircle and Triangle, and we want to add additional method without make any change to this class, so add additional static class which contains the method that we want to inject into Geometri Class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Extension_Method
{
class Geometri
{
public Geometri()
{


}

public double GetCircle(double r)
{
double a = 3.14 * (r * r);


return a;
}


public double Triangel(int a,int t)
{
double l = (0.5 * a) * t;


return l;
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Extension_Method
{
static class ExtensionClass
{
static ExtensionClass()
{


}

static public double square(this Geometri geo, int a)
{
return a * a;
}
}
}

Square method on ExtensionClass class have variable "geo" that point to "Geometri", this means we are going to attach this method on "Geometri" class. Furthermore We should put "static" modifier to ExtensionClass, and finally make instance of "Geometri Class" and you see the square method show up with description as "Extension Method".

Extension method

Bookmark and Share

0 comments:

Post a Comment