0

Here I have a requirement that i need to access the members of objects dynamically Suppose Example I have created a person object with the members Name , Age, gender, Height, Weight and I have a variable with the name personProperty which will hold member names like Some times personProperty = "Name" and sometimes personProperty = "Gender"

So is there any way that i can access like Person.[personProperty] to set or get values from person object

  • Try looking into c# Reflection. – AliK May 08 '20 at 12:40
  • 1
    Does this answer your question? [Get property value from string using reflection in C#](https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – Crowcoder May 08 '20 at 12:41

1 Answers1

0

You can get a Property by name using reflection, like this:

public static object GetPropertyValue(object person, string propName)
{
  return person.GetType().GetProperty(propName).GetValue(propName, null);
}

Or try to cast your object to another defined type...

TWP
  • 250
  • 1
  • 5
  • 13