CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » Csharp Article » Understanding Extension Methods in C#   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

Community News
No News Feeds available at this time.
 
Understanding Extension Methods in C#

By Bala Murugan
Posted On Aug 27,2010
Article Rating: (Login)
Average Rating: 5
No of Ratings: 1
No of Comments: 1
Print this article.
Category: C# 3.0

Subscribe to our feed!

Understanding Extension Methods in C#

 

Extension method is a new feature introduced in C# 3.0. It is a feature where we can add new methods to an existing type without modifying the original source and recompiling it. For example, there will be situation where we need to add a new method to an existing framework class or third party library or even a class contained in your project where you don’t have the source code with you. Traditionally, we will create a derived type to add a new method to an existing type. By using extension method, you can prevent writing a derived type and can add a new method very easily to an existing type, and it can be called similar to calling a method on that type.

Also, you cannot create a derived class if the class is sealed. In this case, we have to use extension method to add a new method.

You can create an extension method for a class or interface in C#.

 

How to declare an extension method?

An extension method should be a static method in a static class. The first argument should be the type to which we are adding the extension method with this modifier.

To demonstrate usage of extension method, we will try to add a extension method called StripHTMLTags() to String class which will strip the html tags contained in the string.

 

using System;

using System.Text.RegularExpressions;

namespace ExtensionDemo

{

public static class StringExtension

{

public static string StripHTMLTags(this string str)

{

string expn = "<.*?>";

return Regex.Replace(str, expn, string.Empty);

}

}

}

 

As I said before, once an extension method is created for a type it can be accessed like a normal instance method. Also, you can see the extension method appearing in the visual studio intellisense for the string type henceforth. Refer the code below,

protected void Page_Load(object sender, EventArgs e)

{

string HTML = "<b>I Love ASP.Net!!</b>";

Response.Write(HTML.StripHTMLTags());

}

 

Extension Methods in Action in C#

 

Scope of extension method

To call the extension method one has to import the namespace through using directive where the extension method is defined i.e. you will able to call or visual studio intellisense will show your extension method only when you import the namespace where you have defined your extension method. Refer the code below,

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using ExtensionDemo;

 

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

string HTML = "<b>I Love ASP.Net!!</b>";

Response.Write(HTML.StripHTMLTags());

}

}

 

If the above code did not contain “using ExtensionDemo;” then it will throw a compilation error (even intellisense will not show the method). Once executed, the above code will produce output without html tags.

OUTPUT

Extension Methods in Action in C#

If you create an extension method with similar signature of any methods contained in the type, then your extension method will not be called. In this case, compiler will always give priority to the instance method wherever it is called.

 

using System;

using System.Text.RegularExpressions;

/// <summary>

/// Summary description for StringExtension

/// </summary>

namespace ExtensionDemo

{

public static class StringExtension

{

public static string StripHTMLTags(this string str)

{

string expn = "<.*?>";

return Regex.Replace(str, expn, string.Empty);

}

public static string ToString(this string str)

{

string expn = "<.*?>";

return Regex.Replace(str, expn, string.Empty);

}

}

}

 

In the above code, the second method ToString() has similar signature of ToString() in String class. Hence, calling ToString() on the string instance will always call the original implementation and not the extension method. If you execute the below code, the output will contain the html tags in the string variable HTML.

 



ASP.Net Hosting

Recent Articles

protected void Page_Load(object sender, EventArgs e)

{

string HTML = "<b>I Love ASP.Net!!</b>";

Response.Write(HTML.ToString());

}

 

OUTPUT

Extension Methods in Action in C#

 

Conclusion

Like partial class, extension method adds another big capability to C# language which can be used to add additional methods without re-compiling the class code. Also, .NetFramework already uses extension methods extensively in LINQ in System.Linq namespace for the types like IEnumerable, etc. You can see this when you import System.Linq namespace and bring those extension methods in scope.

Similar Articles
  • You can contribute to CodeDigest.Com:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments
    Nice Code
    Nice code for html tag with Ajax regex code