5

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+?

casperOne
  • 73,706
  • 19
  • 184
  • 253
Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162
  • Does this answer your question? [Can I add extension methods to an existing static class?](https://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class) – StayOnTarget Nov 17 '20 at 23:11

1 Answers1

3

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.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • +1 This is indeed a good explanation. Aside, I cannot think of a particular way to make it possible, though there might or might not be a way to implement such feature. Perhaps by simply putting a 'static' keyword before 'this' or before the type itself only would suffice, though I can't say anything regarding the impacts that it may have to make it this way. Thanks for your time! =) – Will Marcouiller Nov 09 '11 at 05:10