How to get a property value based on the name How to get a property value based on the name asp.net asp.net

How to get a property value based on the name


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


You'd have to use reflection

public object GetPropertyValue(object car, string propertyName){   return car.GetType().GetProperties()      .Single(pi => pi.Name == propertyName)      .GetValue(car, null);}

If you want to be really fancy, you could make it an extension method:

public static object GetPropertyValue(this object car, string propertyName){   return car.GetType().GetProperties()      .Single(pi => pi.Name == propertyName)      .GetValue(car, null);}

And then:

string makeValue = (string)car.GetPropertyValue("Make");


You want Reflection

Type t = typeof(Car);PropertyInfo prop = t.GetProperty("Make");if(null != prop)return prop.GetValue(this, null);