Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top