Reference to an attribute of a class by means of a string containing the name of the property

Let's take a very short example of a class like this:

Public Class The_Class1
    Public Property ID As Integer
    Public Property Property1_Integer As Integer
    Public Property Property2_Single As Single
End Class

Somewhere else, I have a dictionary containing instances of The_Class1, like this:

Public Dictionary_Class1 As New Dictionary(Of Integer, The_Class1)

I want to perform an operation over Property1_Integer on all of the members inside Dictionary_Class1. Also, I want to perform the very same operation over Property2_Single, so I would like to create a function to perform such operation, and somehow instruct VB to use a given property on every call.

Can you think of an elegant way to do that?

Edit: Let's say, for example, that the operation that I want to perform is the sum of every Property1_Integer or Property2_Single of the members inside the dictionary. What I really really want to do is to determine if all of the values are the same, or if there is at least one that is different.

Upvotes: 0

Views: 46

Answers (1)

laancelot
laancelot

Reputation: 3207

You can use Reflection, but it's not as clean as you may imagine. Here's some skeleton code you can adapt to your needs:

Public Class The_Class1
    Public Property ID As Integer
    Public Property Property1_Integer As Integer
    Public Property Property2_Single As Single
End Class

Private Sub SetProperty1_Integer()
    Dim myClassInstance As New The_Class1
    Dim myType As Type = GetType(The_Class1)
    Dim propertyInfo As System.Reflection.PropertyInfo = myType.GetProperty("Property1_Integer")

    propertyInfo.SetValue(myClassInstance, 1)
    MessageBox.Show(myClassInstance.Property1_Integer.ToString)
End Sub

Have fun!

Upvotes: 1

Related Questions