I have a field in a class with a random name like:
class Foo {
public string a2de = "e2"
}
I have the name of this field in another variable like:
string vari = "a2de"
Can I get or set the value of field a2de
by using the value of vari
?
like:
getvar(vari)
or
setvar(vari) = "e3"
You have to use reflection.
To get the value of a property on
targetObject
:To get the value of a field it's similar:
If the property/field is not public or it has been inherited from a base class, you will need to provide explicit
BindingFlags
toGetProperty
orGetField
.You'd have to use Reflection to access the variable by name. Like this:
You can potentially do it with reflection (e.g.
Type.GetField
etc) - but that should generally be a last resort.Have you considered using a
Dictionary<string, string>
and using the "variable name" as the key instead?