3

Why is it no possible to declare / implement an Extension-Method in a class which isn´t static?

I know that an Extension-Method is for non-instantiable types useless. But why not implement it in a instantiable class? What is the reason for this? Is it a technical issue or just to find the methods faster or to force better software design?

0xDEADBEEF
  • 3,401
  • 8
  • 37
  • 66
  • possible duplicate of [Why aren't C# static class extension methods supported?](http://stackoverflow.com/questions/4909156/why-arent-c-sharp-static-class-extension-methods-supported) – Reed Copsey Jul 23 '13 at 18:25
  • Duplicate of http://stackoverflow.com/questions/3930335/why-are-extension-methods-only-allowed-in-non-nested-non-generic-static-class – Andrew Coonce Jul 23 '13 at 18:26

2 Answers2

1

You can define a class as static if you want to guarantee that it can't be instantiated, can't derive from or serve as the base for another type, and can contain only static members.

http://msdn.microsoft.com/en-us/library/vstudio/79b3xss3.aspx

Having extension methods being edit: static new'd in child classes and such would be a real pain.

As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded.

Static classes are higher on the initialization priority chain, making the implementation a bit more efficient.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • 1
    I would assume that even in a non-static class, the extension methods themselves would still require to be `static`, thus you wouldn't be able to override them anyway. – Chris Sinclair Jul 23 '13 at 18:34
  • @ChrisSinclair - I meant the new modifier http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx#vclrfnew_newmodifier – Louis Ricci Jul 23 '13 at 18:40
  • Same difference. The static methods belong with the type they're declared on. Hiding static methods using `new` only has an effect when internally in the class (or its derived subclasses) call the static methods without explicitly indicating the type. Unless you're suggesting that if you declared an extension method on base class `Bar` in namespace `A`, declared a derived class `Foo : Bar` in namespace `B`, then added `using B;` to import extension methods from `B.Foo`, it would crawl up and grab extension methods from `A.Bar` too? **Scary** – Chris Sinclair Jul 23 '13 at 19:26
0

LINQ only needs extension methods in static, non-generic, non-nested classes to work, so that's how it is designed and implemented. Had it been required for non-static, generic, nested classes it would have been implemented that way.

Ehsan
  • 31,833
  • 6
  • 56
  • 65