How to write Extension method in a Non Static class in C# .Net

Last Reply on Jan 13, 2015 03:46 AM By Mudassar

Posted on Jan 09, 2015 03:31 AM

Hi,

      Kindly inform whether we can create a Extension method in a Non-Static class. If yes please explain how and if not kindly inform why we can't. Thanks in advance.

Posted on Jan 13, 2015 03:46 AM

Yes. It is compulsion that the Extension method must be in a Static class only so that only one Instance is created.

For example, if you place the following in ASP.Net page it will not work. Though error will not come, but you will not see the method available.

public partial class _Default : System.Web.UI.Page
{
    public static bool CompareString(this string value1, string value2)
    {
        return value1.Equals(value2);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        bool isEqual = "Mudassar".CompareString("Khan");
   }
}

The above will not work. But when I create a Static class it will start working.

public static class Extensions
{
    public static bool CompareString(this string value1, string value2)
    {
        return value1.Equals(value2);
    }
}

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

    protected void Page_Load(object sender, EventArgs e)
    {
        bool isEqual = "Mudassar".CompareString("Khan");
   }
}