[This post is part of a series, "wish-list for future versions of VB"]

 

IDEA: Extension properties. We should add extension properties, just like we have extension methods.

 

SCENARIO: In Javascript and a host of web-related DSLs, there are many attempts at a easy syntax for constructing HTML elements, but none of them really pull it off succesfully. VB with its XML literals could do a better job, especially with extension properties:

    doc.getElementById("div").innerNodes = <ul><li>Hello</li><li>World</li></ul>

 

    <Runtime.CompilerServices.Extension()>

    WriteOnly Property innerNodes(ByVal x As HtmlElement) As XElement

        Set(ByVal value As XElement)

            x.Add(... value ... need to do some munging here)

        End Set

    End Property

 

On Internet Explorer, people sometimes use ".innerHTML" instead and then ask the browser to parse this text string. But this doesn't work on Firefox, and isn't as fast as creating the nodes directly.

 

SCENARIO: User "Eidolon II" suggests, for the Session object in an ASP.NET project, using extension properties to wrap session variables. Currently it needs to be done by adding an extension Sub getter and extension function setter accessors.

    <Runtime.CompilerServices.Extension()>

    Public Property SelectedProductId(ByVal target As HttpSessionState) As Integer

        Get

            Return target("selprodid")

        End Get

        Set(ByVal value As Integer)

            target("selprodid") = value

        End Set

    End Property

 

Did you know that VB already has extension properties? More precisely, it has three extension properties for working with XML:

        Dim x = <xml><a>hello</a></xml>

        Dim y = x.<a>.Value

Here x.<a> returns an IEnumerable(Of XElement), and "Value" is an extension property on that. It's defined inside InternalXMLHelper, a class that we spit out into any user assembly that uses XML literals. We didn't extend extension-properties to a full user-usable feature because that would have involved a lot more design work, and testing, and we ran into places where extension properties wouldn't even do what we wanted them to.

 

Provisional evaluation from VB team: This is a decent idea, one worth considering against the other decent ideas. If you see more scenarios where extension properties would help you, please write about them! Or if they wouldn't help your particular scenarios, then please write in about those as well.