What is an Extension Method?
Extension methods enable us to add new methods to existing types.
Then what makes it so different?
Step 1
Create a static class called PageExtensions as:
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:
That's it, for the client code there will not be any difference between normal methods and Extension methods.
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).
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:
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));
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.
No comments:
Post a Comment