In this article we will create some extension methods for an ASP.Net application.
What is an Extension Method?
Extension methods enable us to add new methods to existing types.
Then what makes it so different?
- To do it we are not required to modify the existing type.
- No Inheritance is involved.
- They are static by nature (but called as if they are instance methods on the extended type).
How to create?
Step 1
Create a static class called PageExtensions as:
public static class ClsPageExtenions
{
}
Step 2
Create a static method IncludeJavaScript and IncludeStylesheet in that class as:
public static void IncludeJavascript(this Page objPage, string strJsPath)
{
HtmlGenericControl objJs = new HtmlGenericControl();
objJs.TagName = "script";
objJs.Attributes.Add("type", "text/javascript");
objJs.Attributes.Add("language", "javascript");
objJs.Attributes.Add("src", objPage.ResolveClientUrl("~/Javascript/" +
strJsPath));
objPage.Header.Controls.Add(objJs);
}
public static void IncludeStylesheet(this Page objPage, string strCssPath)
{
HtmlGenericControl objCss = new HtmlGenericControl();
objCss.TagName = "link";
objCss.Attributes.Add("type", "text/css");
objCss.Attributes.Add("rel", "stylesheet");
objCss.Attributes.Add("href", objPage.ResolveClientUrl("~/CSS/" + strCssPath));
objPage.Header.Controls.Add(objCss);
}
Note: The first parameter must be preceded this modifier, telling the compiler that this is an extension method for the Page Class.
Step 3
Create the client code as:
protected void Page_Load(object sender, EventArgs e)
{
this.IncludeJavascript("MyJs.js");
this.IncludeStylesheet("MyCss.css");
}
That's it, for the client code there will not be any difference between normal methods and Extension methods.
You can download the attached source code for a complete demonstration.
Feedback and comments are always welcome.
Stay tuned for more articles.