Req16: Modules that don't auto-import their contents; extension methods in classes.
[This post is part of a series, "wish-list for future versions of VB"]
IDEA 1: Shared Classes. We should allow "Shared Classes". Their members are all implicitly shared (like a Module), they can't be instantiated (like a Module), but their contents won't be auto-imported:
f1() ' allowed
f2() ' disallowed
M1.f1() ' allowed
C2.f2() ' allowed
Module M1
Public Sub f1()
End Sub
End Module
Shared Class C2
Public Sub f2()
End Sub
End Class
IDEA 2: An <DontImportModuleContents> attribute on modules. We should have an attribute, Microsoft.VisualBasic.DontImportModuleContentsAttribute, which prevents the contents of a module from being auto-imported.
Provisional evaluation from VB team: Instead of these ideas, there's an easy workaround that works already: just stick your shared methods inside a Class rather than a Module. The only thing you don't get from this is that the compiler doesn't enforce the discipline that everything is shared -- but this is a very small shortcoming, and not worth changing the language for.
The workaround doesn't work for extension methods, though: they have to go inside Modules. And their presence inside Modules is awkward because they then appear in intellisense as normal methods (as well as extension methods). Well, that's a shame, but it could be mitigated a little by an IDE fix -- having them appear on the "All" tab rather than the "Common" tab. And it doesn't seem worth changing the language for this one reason.
IDEA 3: Allow extension methods to be defined in classes. Currently all extension methods must be defined in modules. But imagine if we could define them in classes. There are two possible ways to do this:
- Maybe the extension methods are only visible within the current class (and subclasses). This would be a nice way to scope extension methods.
- Or maybe the extension methods would be visible everywhere. This would be a workaround for the above issue (of extension methods appearing in intellisense).
This Idea3.1 seems like it might be useful, but also definitely confusing. What do you think? Have you ever wanted more control over the scope of extension methods?