Monday 24 June 2013

What are Extension Methods

Extension methods allows you to add new functionality for existing data types Without modifying the code of the type itself  This allows you to create new methods for a class which you have no access or those classes which are sealed and you can’t inherit. Extension Methods were introduced in C# 3.0 .
In order to create a extension method you need to create a static class with a static method and use the this keyword.
eg:



public static class ExtensionMethod
{
public static void OutputToConsole(this string s)
    {
        Console.WriteLine(s);
    }
}
so now its use
string s ="Extension mEthod";

s.OutputToConsole();

so now you see string does not have any method called OutputToConsole but when you specify the this keyword all the string varibles will be able to access this function
So now a thing which .net uses is Extension Methods Along with Generics In Linqu
this is what it does
eg:
public static class ExtensionMethod
{
public static void OutputToConsole<T>(this T s)
    {
        Console.WriteLine(s.toString());
    }
}
now this function is accessible to all types
so now its use
string s ="Extension mEthod";
s.OutputToConsole();
int i=1;
i.OutputToConsole();


About Author:
Steven Pinto is technology geek and loves to write on technology. He works in Systems Plus and actively contributes to technology. To more of interesting topics written by Steven, follow http://mad4teck.blogspot.in/

No comments:

Post a Comment