Req17: Define extension methods in an "extension class" of the extended type
[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
<Runtime.CompilerServices.Extension>
Class String
<Runtime.CompilerServices.Extension()>
Sub LogToDisk()
My.Computer.FileSystem.WriteAllText("c:\log.txt", Me, True)
End Sub
<Runtime.CompilerServices.Extension()>
ReadOnly Property p As Integer
Get
Return Me.Length + 42
End Get
End Property
End Class
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".
Class Fred
<Runtime.CompilerServices.Extension()>
Function ToString2() As String
If Me Is Nothing Then Return "_"
Return Me.ToString()
End Function
Public Overrides Function ToString() As String
Return "hello fred"
End Function
End Class
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.