Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type
An extension method is a static method, but with the first parameter it takes being explicitly marked as receiving the object that the method was called on.Extension methods may only appear in static classes but you cannot write an extension methods for another static class.
Extension methods require an instance of an object. You can however, write a static wrapper around
Sample1
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
Extension method using Wrapper
static class Extensions
{
public static long MakeCode(this SerialGenerator SG,
int ProductID, UserInfo User)// Extension method for the Make Code method of serial Generator Class.
{
return SG.MakeCode(ProductID, User.Name, User.DOB,
User.CountryCode);
}
}
Attaching implementation to Interfaces
Extension methods allows to attach implementation to interfaces, I think this is an easy way to attach implementation to the interface which is not possible in any other way as purpose of interface is to only define and not implement.
Sample
public static class Extension
{
public static void MethodA(this IMyInterface myInterface, int i)
{
Console.WriteLine("Extension.MethodA(this IMyInterface myInterface, int i)");
}
When to use Extension Methods
Though inheritance is one of the preferred way of preferred way of extending functionality to a class , the following are the few cases where you can think about writing an extension method :- ref:-http://www.programmersheaven.com/2/CSharp3-2
- If the class is sealed, you will be unable to inherit from it. In this case, you have no option but to use extension methods
- You may be using some kind of object factory that instantiates objects of a given class, but you do not have the ability to modify it so that your subclass is instantiated instead.
- Attaching Method implementation to the Interfaces (You want to implement a method that can be invoked on all classes implementing a given interface)
- You may want to add related things to a number of other classes as like extending functionality to the string class etc... This will avoid spreading of similar functionality in different places.
More details:-http://msdn.microsoft.com/en-us/library/bb383977.aspx
http://www.programmersheaven.com/2/CSharp3-2
No comments:
Post a Comment