C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Extension Methods in C#3.0


Posted Date: 16 May 2006    Resource Type: Articles    Category: .NET Framework
Author: phanindra yerraMember Level: Gold    
Rating: 1 out of 5Points: 10



Introduction



C# 3.0 code named orcas introduces several language enhancements. some of the extensions are
Implicitly typed local variables, Lambda expressions, Object initializers, Anonymous types, Implicitly typed arrays, Query expressions, Expression trees and Extension methods
This article is explaining Extension methods only.

Extension methods:
These methods are static methods can be invoked using instance method syntax, which make it possible to extend existing types and constructed types with additional methods.


Extension Methods



These methods are static methods can be invoked using instance method syntax, which make it possible to extend existing types and constructed types with additional methods.

Declaring :

Extension methods are declared by specifying the keyword this as a modifier on the first parameter of the methods. Extension methods can only be declared in static classes. The following is an example of a static class that declares two extension methods:

namespace Acme.Utilities
{
public static class Extensions
{
public static int ToInt32(this string s) {
return Int32.Parse(s);
}
public static T[] Slice(this T[] source, int index, int count) {
if (index < 0 || count < 0 || source.Length – index < count)
throw new ArgumentException();
T[] result = new T[count];
Array.Copy(source, index, result, 0, count);
return result;
}
}
}


Difference between extension methods and static methods
1. Extension methods have the keyword this before the first argument. Static methods do not have the this keyword in its argument declaration.
2. Extension methods can be defined only in a static class. For static methods, this is not a requirement. Static methods can exist in a regular class as well as in a static class.
3. Extension methods can be called only on instances values.

Extension methods have all the capabilities of regular static methods. In addition, once imported, extension methods can be invoked using instance method syntax.
Importing
Extension methods are imported through using-namespace-directives. In addition to importing the types contained in a namespace, a using-namespace-directive imports all extension methods in all static classes in the namespace. In effect, imported extension methods appear as additional methods on the types that are given by their first parameter and have lower precedence than regular instance methods. For example, when the Acme.Utilities namespace from the example above is imported with the using-namespace-directive

using Acme.Utilities;
it becomes possible to invoke the extension methods in the static class Extensions using instance method syntax:
string s = "1234";
int i = s.ToInt32(); // Same as Extensions.ToInt32(s)
int[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] a = digits.Slice(4, 3); // Same as Extensions.Slice(digits, 4, 3)


Extension method invocations

Sno Method Invocation Compiled codeAs
1 expr . identifier ( ) identifier (expr)
2 expr . identifier ( args ) identifier (expr, args)
3 expr . identifier ( ) identifier (expr)
4 expr . identifier ( args ) identifier (expr, args)

The rewritten form is then processed as a static method invocation, except for the way in which identifier is resolved: Starting with the closest enclosing namespace declaration, continuing with each enclosing namespace declaration, and ending with the containing compilation unit, successive attempts are made to process the rewritten method invocation with a method group consisting of all accessible extension methods with the name given by identifier imported by the namespace declaration’s using-namespace-directives. The first method group that yields a non-empty set of candidate methods is the one chosen for the rewritten method invocation. If all attempts yield empty sets of candidate methods, a compile-time error occurs.
The preceeding rules mean that instance methods take precedence over extension methods, and extension methods imported in inner namespace declarations take precedence over extension methods imported in outer namespace declarations. For example:

using N1;
namespace N1
{
public static class E
{
public static void F(this object obj, int i) { }
public static void F(this object obj, string s) { }
}
}
class A { }
class B
{
public void F(int i) { }
}
class C
{
public void F(object obj) { }
}
class X
{
static void Test(A a, B b, C c) {
a.F(1); // E.F(object, int)
a.F("hello"); // E.F(object, string)
b.F(1); // B.F(int)
b.F("hello"); // E.F(object, string)
c.F(1); // C.F(object)
c.F("hello"); // C.F(object)
}
}


In the example, B’s method takes precedence over the first extension method, and C’s method takes precedence over both extension methods.

Use Of Extension Methods
I think u already got why we need this methods .but one may ask "Why should we use extension methods when I have the regular static and instance methods?" Well, the answer simply is utter convenience. Here is an example. Suppose you developed a library of functions over a period of years. Now, when someone wants to use that function library, the consumer must know the class name that defines the desired static method. Something like the following, for example:
A = MyClass.
At this point, IntelliSense will pop in and give you the names of the available functions. You just have to pick the one you need.
You then type your desired methods and pass the necessary argument:
A = MyClass.DesiredFunction(strName)
With this approach, you need to know beforehand which library contains your desired function and its name. With extension methods, it is more natural—something like the following:
a = str.

At this point, it shows which extension methods are available. You simply type the extension method you want like this
a = str.DesiredFunction()
No arguments are needed to identity the data type on which this method needs to work.
Note:
Extension methods provide a new mechanism for invoking static methods on object instances. But, as per C# 3.0 language specifications, extension methods are less discoverable and more limited in functionality than instance methods. Therefore, you should use extension methods sparingly, only where instance methods are not feasible.
Also, C# 3.0 is not yet an official release, so its specifications are not finalized. Therefore, the syntax is liable to change.


Summary






Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Coalescing operators ,object initializers and var type in new C#
Previous Resource: Collection Class module
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use