Jitesh Byahut 2/25/2014 2444

Extension Methods In C#

Extension methods provide you the opportunity to extend an existing class or type by adding a new method or methods without modifying the original class or type and without recompiling that class or type.

The reason you might want to do this is to add functionality to an existing type without extending the entire class or type.

So, exactly how do you create extension methods? First, you need to include the extension method in a public static class, so first you must create that class. After the class is created, you define the method inside that class and make the method an extension method with the simple addition of the keyword this.

Remember the keyword this refers to the specific instance of the class in which it appears.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        int a = 10;

        int num = a.Square();

    }

}

 

public static class ExtensionSquare

{

    public static int Square(this int num)

    {

        return num * num;

    }

}



Please give your feedback for improving this page