Get class property value where name in variable

R

rambalep

I need to get a class property value, where property name is contained
in a variable.

example:
class test
dim p1 as string
dim p2 as string
end class
....
sub x
dim t as test
dim myvar as string = "p1"
....
'I need to read a property of object t and the name of property is in
"myvar"
?

How can I do it?
Thanks
 
C

Carlos J. Quintero [VB MVP]

Class test
Dim p1 As String
Dim p2 As String

Sub New(ByVal par1 As String, ByVal par2 As String)
p1 = par1
p2 = par2
End Sub
End Class

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim t As test
Dim myvar As String = "p1"
Dim objFieldInfo As System.Reflection.FieldInfo

t = New test("A", "B")

objFieldInfo = GetType(test).GetField(myvar,
Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)

MsgBox(objFieldInfo.GetValue(t).ToString) ' returns "A"

End Sub
--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com
 
L

Larry Lard

rambalep said:
I need to get a class property value, where property name is contained
in a variable.

example:
class test
dim p1 as string
dim p2 as string
end class
...
sub x
dim t as test
dim myvar as string = "p1"
...
'I need to read a property of object t and the name of property is in
"myvar"

Carlos has given you code to do this, but it's worth pointing out that
if you find yourself having to use reflection in 'normal' code, it
probably means your design is wrong.

It's hard to tell from this barebones example but it looks like you
want a String -> String Dictionary, as implemented for example by a
simple Hashtable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top