none
Extension Properties RRS feed

  • General discussion

  • I'm not sure where feature requests go, but I for one would love to see Properties be able to be extensions.  I can live with the fact that there's no storage for the property, but there are a several cases where extension properties would come in really handy.

     

    Examples include facade patterns that either simplify an operation such as using reflection to get/set any property by name or simplifying multi property get/set (say adding a Date property to a class with only Month, Day, Year properties), combining existing Functions and Subroutines into properites etc.

    Public Module Utility

    <Extension()> _

    Public Property Value(ByVal obj As Object, ByVal propName As String) As Object

    Get

    Dim typ = obj.GetType

    Dim pi = typ.GetProperty(propName)

    If pi Is Nothing Then Return Nothing

    Return pi.GetValue(obj, Nothing)

    End Get

    Set(ByVal value As Object)

    Dim typ = obj.GetType

    Dim pi = typ.GetProperty(propName)

    pi.SetValue(obj, value, Nothing)

    End Set

    End Property

    End Module

     

    Other examples might include conversion properties.  Say adding a Mhz property to a Computer class with CpuSpeed, Serialization/Deserialization, Explicit Bi-directional type casting.

     

    In addition if an additional value is truly required, implementing shared dictionaries or hashtables of objects with the values being referenced by an object reference could provide any level of complex storage requirements transparent to the original class.  Consider the following example of adding a Date property all objects:

    Public Module Utility

    Private _dates As New Dictionary(Of Object, Date)

    <Extension()> _

    Public Property DateAdded(ByVal obj As Object) As Date

    Get

    If _dates.ContainsKey(obj) Then

    Return _dates(obj)

    Else

    Return Nothing

    End If

    End Get

    Set(ByVal value As Date)

    If _dates.ContainsKey(obj) Then

    _dates(obj) = value

    Else

    _dates.Add(obj, value)

    End If

    End Set

    End Property

    End Module

     

    I for one find many instances where extending Extensions to include properties as well as functions and subroutines would be a great boon. 

    Wednesday, April 16, 2008 11:40 PM

All replies