How to get a property value based on the name

Coder 2 picture Coder 2 · Apr 1, 2011 · Viewed 179k times · Source

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;
}

Answer

Matt Greer picture Matt Greer · Apr 1, 2011
return car.GetType().GetProperty(propertyName).GetValue(car, null);