SIGN UP MEMBER LOGIN:    
ARTICLE

Extension Methods in .NET

Posted by Rishi Mishra Articles | Visual C# February 06, 2012
To put it in a simple manner, Extension Methods have been introduced in the .NET 3.5 framework to add methods to a class without altering the code of that class.
Reader Level:

To put it in a simple manner, Extension Methods have been introduced in .NET 3.5 framework to add methods to a class without altering the code of that class. Most of the times you don't have access to create your own methods in the third party dlls and you want to write your own method in that class, then the first question comes in your mind, how will I handle it?

The answer is simple: "Extension Methods".

Why Extension Method: Another question is, why do we need to use the extension methods, we can create our own methods in client application or in other class library and we can call those methods from the client application but the important point is, these methods would not be the part of that class (class of the third party dll). So adding the extension methods in the class, you are indirectly including another behavior in that class. I am talking about the class which is the part of the third party dll (Most Important).

So when you create your own extension methods for specific types those methods would be accessible for that type.

This can be easily understood by the following diagram:

ExMtd1.gif

(I am object of the class)

After some time, client application wants to add another behavior in that class; let's say 'talk' then extension methods can be used to add this extra behavior in that class without altering any code.

ExMtd2.gif

Implementation: The following is the structure of the third party class, which is not accessible to the developer. This class contains a method 'Walk'.

public class Class1
{
    public String Walk()
    {
        return "I can Walk";
    }
}

Now it's time to create the Extension Method. Just use the following steps:

Step 1: Create the Static Class

Step 2: Create the Static Method and give any logical name to it.

Step 3: In the Extension Method Parameter, just pass this along with the object type and
the object name as given below:

ExMtd3.gif

The client application can access both the method "Walk" and the extension method "TalkExtMethod":

Class1 obj = new Class1 ();

Obj.TalkExtMethod () 
obj.Walk ()


Benefits: There may be various benefits of using the Extension Methods in your code. Let's say you are using the method1 () of the class in the third party dll and the object instantiation has failed due to another reason; then you will get the object reference error while calling the method1 () if you did not handle the null reference check.

Class1 obj = GetClass1Object ();
//If the obj is null, you will get the object reference error
obj.Method1();

Although the following code is safer than previous one but the problem is you will have to include this check every time when you call the Method1 and if the developer forgets to include this check in the code then the program throws an object reference error.

Class1 obj = GetClass1Object ();
if (obj!= null)
{
    obj.Method1 ();
}

If we use the extension method to solve this problem we get outstanding results. Instead of checking the null reference every time in the code we handle it in the extension methods which is called by the client application.

public static string Method1ExtMethod(this Class1 objClass)
{
    //If the obj is not null, then call the Method1()

    if (objClass! = null)
    {
        return objClass.Method1 ();
    }
    return string.Empty;   
}

Class1 obj = GetClass1Object ();
//Don't include any check whether the object is null or not
obj.Method1ExtMethod()

Login to add your contents and source code to this article
share this article :
post comment
 

You have presented your article nicely.

Posted by Daisy Krause Feb 07, 2012

Can we use private members of the class for which this extension method is added?

Posted by Brij Mishra Feb 06, 2012
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor