[This post is part of a series, "wish-list for future versions of VB"]
IDEA: Allow extension methods to be defined in their "extension class". It would look like this:
Dim x = "hello"
x.LogToDisk() ' extension method defined on strings
Dim y = x.p ' extension property defined on strings
My.Computer.FileSystem.WriteAllText("c:\log.txt", Me, True)
ReadOnly Property p As Integer
Return Me.Length + 42
This would be a useful syntax for defining extension properties. It would also allow tricks like the following: code that looks like a method, but is robust against being called on a "null reference".
Function ToString2() As String
If Me Is Nothing Then Return "_"
Public Overrides Function ToString() As String
Return "hello fred"
Provisional evaluation from VB team: It's bad enough that extension methods currently work on a null "Me" pointer already. We don't think it's good language design to make such a thing even easier: it feels like it would lead to more confusion than readability.