Extension Methods in C#3.0

Learner
Posted by in C# category on for Beginner level | Views : 5696 red flag
Rating: 5 out of 5  
 1 vote(s)

I just read about Extension methods so thought to write about it so as to give brief idea about this feature introduced in C# 3.0.

Extension Methods:static methods that you can invoke using the instance method syntax.
Introduction
Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.

 

Extension method behavior is similar to that of static methods. You can declare them only in static classes. To declare an extension method, you specify the keyword this as the first parameter of the method, for example:

public static class Abc

{

static void extPrint(this string s)
        {
            Console.WriteLine(s);
        }
static void staticPrint(string s)
        {
            Console.WriteLine(s);
        }
}


class Program
{
        static void Main(string[] args)
        {

            "A".extPrint();                     --------- Print A
            staticPrint("Hello");              --------- Print Hello
        }
}

As you can see from the above snippet, the differences between the extension method extPrint() and the regular static method (staticPrint) are the following:

  1. Extension methods have the keyword this before the first argument. Static methods do not have the this keyword in its argument declaration.
  2. When extension methods are consumed, the argument that was declared with the keyword this is not passed. In the above code, A is an example of consuming the extension method extPrint. No argument is passed to it. When static methods are consumed, no arguments are skipped. All expected arguments must be entered. Hello is an example of this.
  3. 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.
  4. Extension methods can be called only on instances values.


Page copy protected against web site content infringement by Copyscape

About the Author

Learner
Full Name: Nikki Verma
Member Level: Starter
Member Status: Member
Member Since: 12/16/2008 12:38:53 AM
Country:



Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)