allow extension methods to be defined in instance classes
Currently, extension methods can only be defined in a static class. It would be very helpful if an extension method could also be defined in an instance class, so that this was possible:
public class Foo
public void DoBar()
private static Baz GetBaz(this IQux qux, string s)
// Get Baz from qux here...
This simply enables a more fluent syntax for private helper methods. This can improve readability of the code compared to a more procedural-looking use of normal static helper methods.
The current workaround is to define a new internal static class, but that opens those helper methods to be used from other classes in the assembly, and sometimes such private helper methods aren't ready for that (they may not properly protect their invariants).
An alternative to the above code would be to allow extension methods to be defined in (private) nested classes.
Wouter Vos commented
Seems to me extension methods are quite a change and can be unexpected by other programmers. Allowing any class to extend any other class goes in against the separation of responsibilities.
Instead, define a separate class for all extension methods on a specific class, ClassNameExtensions. Yes this will lead to more codefiles, but at least it's clear where all extension methods are located.
Dan Rabb commented
This seems like a limitation of the C# specification, and not Visual Studio.
Nobody Real commented
I doubt anything like this will happen, since extension methods are only possible because they are static. To put this another way, extension methods are just syntactic sugar over a call like this: myObject.MyExtension() is really MyExtension(myObject). In other words, extension methods don't *REALLY* add methods to objects, it just pretends to do. They would essentially have to change the basic nature of the object model, making all objects dynamic in order to do this, and I don't see that happening.. and if it did, we probably wouldn't like it.
It's funny, you know, I had thought of this some time ago and I got persuaded to the opposite (see this: http://social.msdn.microsoft.com/Forums/nl/csharpgeneral/thread/6618afba-9cad-4322-a5f3-e4391ae35f03). Indeed, I now look at this in a different way than back then. It doesn't sound very good nor helpful.
As a workaround, you can make a separate namespace for the extension method.