Saturday, 10 December 2011

C# 3.5 Extension Methods

In C# 3.5 introduces many new features like anonymous method ,extension method and var keyword
In this we will introduce Extension Methods

What is Extension Methods

1.Extension methods allow an existing type to be extended with new methods without altering the definition of the original type. 
2.An extension method is a static method of a static class, where the this modifier is applied to the first parameter. 
3.The type of the first parameter will be the type that is extended.


public static class StringHelper
public static bool IsCapitalized (this string s)
if (string.IsNullOrEmpty(s)) return false;
return char.IsUpper (s[0]);

4.The IsCapitalized extension method can be called as though it were an instance method on a string.

String s = "Perth“;
Console.WriteLine (s.IsCapitalized());

5.An extension method call, when compiled, is translated back into an ordinary static method call.
Console.WriteLine (StringHelper.IsCapitalized (s));

Ambiguity and Resolution about Extension Methods

1.An extension method cannot be accessed unless the namespace is in scope.

2.Any compatible instance method will always take precedence over an extension method.

3. If two extension methods have the same signature, the extension method must be called as an ordinary static method to disambiguate the method to call. 

4.If one extension method has more specific arguments, however, the more specific method takes precedence.

Example :-

static class StringHelper
public static bool IsCapitalized (this string s) {...}
static class ObjectHelper
public static bool IsCapitalized (this object s) {...}

bool test1 = "Perth".IsCapitalized();
bool test2 = (ObjectHelper.IsCapitalized ("Perth"));