tocqueville tocqueville - 5 months ago 17
C# Question

C# extension method only working with an instance of the class. Any way around it?

As far as I know, C# only let us use extension methods with an instance of a class:

public class MyClass
{
public static string GetStuff()
{
return string.Empty;
}
}

public static class MyClassExtension
{
public static string GetOtherStuff(this MyClass myClass)
{
return string.Empty;
}
}


Usage:

MyClass.GetStuff();
MyClass.GetOtherStuff(); // Cannot resolve symbol 'GetOtherStuff'
new MyClass().GetOtherStuff(); // This works


However, I noticed that the MVC framework allows me to extend the HtmlHelpers in such a way that I can use my extension methods without creating any instance of a class. For example, if I create an extension method for
HtmlHelper
like this:

public static string MyHtmlHelper(this HtmlHelper helper)
{
return string.Empty;
}


I can use it in a Razor View like this:

@Html.MyHtmlHelper() // no need to instantiate a class


I would really like to achieve the same result with my
MyClass
, so I can do:

MyClass.GetOtherStuff()


How could I do that?

Answer Source

I ended up implementing MyClass using the Singleton pattern

public class MyClass
{
    private MyClass()
    {

    }

    private static MyClass _instance = null;

    public static MyClass Instance => _instance ?? (_instance = new MyClass());

    public string GetStuff()
    {
        return string.Empty;
    }
}

This way it can be extended...

public static class MyClassExtension
{
    public static string GetOtherStuff(this MyClass myClass)
    {
        return string.Empty;
    }
}

...but at the same time there is no need to create a new instance of the class every time I want to access its methods. I just access the Singleton Instance property of it:

MyClass.Instance.GetStuff();
MyClass.Instance.GetOtherStuff();