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+?
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
thiskeyword:In the code above, the
thisdecorator is the only thing that instructs the compiler to treatExtendFoo()as an extension method that augments classFoo. In other words, we cannot get rid of parameterfoo, which will refer to the instance ofFooto which the extension method will apply, i.e. the equivalent ofthisif the method was native toFoo. 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
Foois static, then the compiler should emit code that passesnullinstead of an actual instance ofFoo(that cannot exist anyway). But that would be an obvious kludge, and probably shouldn’t be part of the language for this reason only. ExpectNullReferenceExceptionsall over the place otherwise.