What is Extension Method ?

 Posted by dhirenkaunar-15094 on 5/10/2012 | Category: C# Interview questions | Views: 2553 | Points: 40
Answer:

Extension method is a .net language feature which has introduced to C# in .NET 3.0.
Extension methods are a piece of syntactic sugar which allows a developer to add new methods to the public interface of an existing CLR type without deriving a new class or recompiling the original type.
For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. “

Rules to create Extension Method?
1.Extension Methods have to be implemented as static methods and in static classes (inside a non-nested, non-generic static class to be more precise).
We need to add the "this" keyword before the first parameter .The "this" keyword in the function declaration instructs the compiler that the function extends the data type that immediately follows it.
2.You aren't actually adding methods to the class, you can only access the public members from your extension method. Logically, any extension methods that are defined on a type are available to any sub classes of that type.
3.For the extension method to be available, you must include the namespace containing the extension.
4.If the type you are extending has a real method that has the same name as the extension method, the extension method is ignored. This is important as it has comparability implications.
5.Extension methods for properties are not possible.
6.Extension methods cannot access private variables in the type they are extending.

A good example of this is testing a integer to see if it is a even number or a odd number . In order to do this,
//Old methodology
public class intHelper

{
public static bool isEven(int input)
{
if (input % 2 == 0)
{
return true;
}
return false;
}
}

// Calling in the desired place like given below .
bool helperRes = intHelper.isEven(20);

// Using extension method
public static class intExtention

{
public static bool isEven(this int input)
{
if (input % 2 == 0)
{
return true;
}
return false;
}
}

// Calling in the desired place like given below .
int inputValue=20;

bool helperRes = inputValue.isEven();


Source: http://www.extensionmethod.net | Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response