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.

Comments (5)

  1. How about narrowing the scope so that just Enumerations allow extension methods?

    Or even better, just allow Enumerations to have instance methods that are compiled as extension methods in a matching module "[EnumName]Extension".

  2. Adam Speight says:

    I can’t under stand why a Shared Public Method in a Class can not be attributed to be an Extension Method, if the first parameter is of the class type?

  3. Héctor says:

    Don’t like how this is proposed. I agree with Adam. Extensions should be able to be declared as static methods inside not inheritable classes or static classes.

  4. Mark Hurd says:

    How about allowing the second construct (ToString2) with a new NullableMeAttribute, which could even apply to a class to mean it applies to all its "instance" methods and properties.

  5. weitzhandler says:

    Why not have a Shared Class in VB.NET, I think the C# static class is just like a NotInheritable class that all its memebers are shared, it's definitely not a Module.

Skip to main content