Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and set the field value by passing name

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"
like image 272
Luca Romagnoli Avatar asked Dec 06 '22 22:12

Luca Romagnoli


2 Answers

You have to use reflection.

To get the value of a property on targetObject:

var value = targetObject.GetType().GetProperty(vari).GetValue(targetObject, null);

To get the value of a field it's similar:

var value = targetObject.GetType().GetField(vari).GetValue(targetObject, null);

If the property/field is not public or it has been inherited from a base class, you will need to provide explicit BindingFlags to GetProperty or GetField.

like image 58
Jon Avatar answered Dec 25 '22 16:12

Jon


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?

like image 28
Jon Skeet Avatar answered Dec 25 '22 15:12

Jon Skeet