The power of CallByName

Posted Fri, Jul 20 2007 0:44 by bill

Beth and I have been having a argument all in fist fight discussion about dynamic code in VB.  My point to Beth in the discussion was that all the code she showed could in fact be made work reasonably easily with Strict On, such is the power of the CallByName function.  In VB 10 we hopefully will also have dynamic identifiers which were originally touted for VB9.  They'll dramatically reduce the need for CallByName.  From memory I think the syntax suggested was info.("Item")(prop) for the same as the CallByName(info, "Item", CallType.Get, prop)

 

Anyway, here's the code I tried pasting into a comment by the formatting went weird.

 

Shared Function GetQuestion(ByVal info As Object, ByVal properties As List(Of String)) As Object
    Dim c As Object
    Dim propValue As Object
    Try

        Dim assemblyName As String = CStr(CallByName(info, "Item", CallType.Get, "Assembly"))
        Dim controlName As String = CStr(CallByName(info, "Item", CallType.Get, "Control"))
        c = System.Reflection.Assembly.Load(assemblyName).CreateInstance(controlName)

        'VB does an automatic conversion at *runtime* when
        ' working with these properties because we don't
        ' know the info object type nor the property types.
        For Each prop As String In properties
            Try
                propValue = CallByName(info, "Item", CallType.Get, prop)
            Catch ex As Exception
                propValue = Nothing
            End Try

            If propValue IsNot Nothing AndAlso propValue IsNot System.DBNull.Value Then
                Try
                    CallByName(c, prop, CallType.Set, propValue)
                Catch ex As Exception
                    'if we can't set a property on the object, just ignore
                End Try
            End If
        Next

    Catch ex As Exception
        'Try/Catch is required here, as this code will cause
        ' a runtime error if the the type cannot be created.
        Dim tbx As New TextBox
        With tbx
            .Text = ex.ToString
            .Multiline = True
            .Height = 100
            .ReadOnly = True
            .ScrollBars = ScrollBars.Vertical
        End With
        c = tbx
    End Try

    Return c
End Function

Filed under: , , ,