1

I need to call a public property of a class based on the string value of its name, as I won't know until run time what properties are required. I'm trying to use reflections unsuccessfully. The class looks like this:

class FieldCalculation
{
    public string MyValue
    {
        get
        {
            return "Test Data";
        }
    }
}

I think access the value of the property should look something like this:

FieldCalculation myClass = new FieldCalculation();
string value = myClass.GetType().GetProperty("MyValue");

Any help would be appreciated.

CorribView
  • 711
  • 1
  • 19
  • 44
  • 3
    Possible duplicate of [Get property value from string using reflection in C#](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – NineBerry Apr 12 '16 at 00:48
  • Yes, I guess it's a duplicate. But I did find it useful separating out the definition of the FieldCalculation class as I didn't realize that was what had to be passed into the GetValue method – CorribView Apr 12 '16 at 00:55

1 Answers1

3

You nearly had it. What you were doing was getting the property definition. You need to ask that property to get you the value, and you pass it the instance. This is the working code:

FieldCalculation myClass = new FieldCalculation();
string value = (string)myClass.GetType().GetProperty("MyValue").GetValue(myClass);
Rob
  • 26,989
  • 16
  • 82
  • 98