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()
{
new Qux().GetBaz("corge").DoGrault();
}
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.
4 comments
-
Wouter Vos
commented
-1
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.
-
JMCF125 commented
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.
-
SLaks
commented
As a workaround, you can make a separate namespace for the extension method.
http://blog.slaks.net/2011/07/creating-local-extension-methods.html