Dynamically invoke properties by string name using VB.NET

Tom picture Tom · Oct 27, 2008 · Viewed 30.4k times · Source

I'm currently working on a project where a section of the code looks like this:

Select Case oReader.Name
    Case "NameExample1"
        Me.Elements.NameExample1.Value = oReader.ReadString
    ....
    Case "NameExampleN"
        Me.Elements.NameExampleN.Value = oReader.ReadString
    ....
End Select

It continues on for a while. The code is obviously verbose and it feels like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done:

Dim sReadString As String = oReader.ReadString
Me.Elements.InvokeProperty(sReadString).Value = sReadString

Answer

Jonathan Allen picture Jonathan Allen · Oct 30, 2008

I can't believe the other posters told you to use reflection. VB as a CallByName function that does exactly what you want.