How to get a property value based on the name Ask Question

How to get a property value based on the name Ask Question

is there a way to get the value of a property of a object based on its name?

For example if I have:

public class Car : Vehicle
{
   public string Make { get; set; }
}

and

var car = new Car { Make="Ford" };

I want to write a method where I can pass in the property name and it would return the property value. ie:

public string GetPropertyValue(string propertyName)
{
   return the value of the property;
}

ベストアンサー1

return car.GetType().GetProperty(propertyName).GetValue(car, null);

おすすめ記事