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;
}
You want Reflection
You'd have to use reflection
If you want to be really fancy, you could make it an extension method:
And then:
Simple sample (without write reflection hard code in the client)
Expanding on Adam Rackis's answer - we can make the extension method generic simply like this:
You can throw some error handling around that too if you like.
In addition other guys answer, its Easy to get property value of any object by use Extension method like:
Usage is: