0

so basically I have a class that similar to the following but much longer

Public Class inventory
    Public Property id As Integer
    Public Property name As String
End Class

and in other class I have a list of called order of class inventory so when I loop over the list I can do as

For Each i In orders
        Console.WriteLine(i.name)
Next

but I want a variable to be in the spot . so like

Dim rrr As String = Console.ReadLine()
For Each i In orders
     Console.WriteLine(i.rrr)
Next

however I get error as rrr is not a member in inventory! so please any one know how to solve that and be able to access the class from a variable let me know Thanks

DotNetDev
  • 25
  • 4

1 Answers1

1

An answer is provided at Get property value from string using reflection in C# but it is C#. Following is vb.net translation.

Public Class inventory
    Public Property id As Integer
    Public Property name As String
    'I added a custom constructor to make filling a list easier for me
    Public Sub New(i As Integer, n As String)
        id = i
        name = n
    End Sub
    'add back default constructor
    Public Sub New()

    End Sub
End Class

Private orders As New List(Of inventory) From {New inventory(1, "Apples"), New inventory(2, "Oranges"), New inventory(3, "Pears")}

Private Sub OPCode()
    Dim rrr As String = "name" 'Console.ReadLine() as if user typed in name
    For Each i In orders
        Console.WriteLine(GetPropertyValue(i, rrr))
    Next
End Sub

Private Function GetPropertyValue(src As Object, PropName As String) As Object
    Return src.GetType().GetProperty(PropName).GetValue(src, Nothing)
End Function

Output:

Apples

Oranges

Pears

Mary
  • 14,926
  • 3
  • 18
  • 27