Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has extending static classes using extension methods been made possible in .NET 4.0+?

I have read that it is possible to extend static classes in F#, though it was not yet possible in C#. Multiple workarounds are proposed and therefore suggesting that this type of extension could be reasonably useful.

Though the extension methods are defined as static, they work on type instances being extended.

Because nothing allows me to think it is now available, I was wondering whether such feature is now made doable to extend a static class using the extension methods syntax in C# in .NET 4.0+?

like image 369
Will Marcouiller Avatar asked Oct 24 '22 19:10

Will Marcouiller


1 Answers

Augmenting static classes with extension methods probably won't be possible in C# in the reasonable future, unless the language changes the way extension methods are declared.

Imagine we have to add this feature to the language. Extension methods are currently defined as static methods taking an additional parameter decorated with the this keyword:

public class Foo
{
}

public static class ExtensionMethods
{
    public static void ExtendFoo(this Foo foo, string bar)
    {
    }
}

In the code above, the this decorator is the only thing that instructs the compiler to treat ExtendFoo() as an extension method that augments class Foo. In other words, we cannot get rid of parameter foo, which will refer to the instance of Foo to which the extension method will apply, i.e. the equivalent of this if the method was native to Foo. Problem is, static classes cannot be instantiated, so what are we going to pass in that parameter?

We can handwave the problem away and enact that if Foo is static, then the compiler should emit code that passes null instead of an actual instance of Foo (that cannot exist anyway). But that would be an obvious kludge, and probably shouldn't be part of the language for this reason only. Expect NullReferenceExceptions all over the place otherwise.

like image 124
Frédéric Hamidi Avatar answered Oct 26 '22 23:10

Frédéric Hamidi