Lets say I have
class Person
{
public Person(int age, string name)
{
Age = age;
Name = name;
}
public int Age{get;set}
First of all, the example you provided has no Properties. It has private member variables. For properties, you would have something like:
public class Person
{
public int Age { get; private set; }
public string Name { get; private set; }
public Person(int age, string name)
{
Age = age;
Name = name;
}
}
And then using reflection to get the values:
public object GetVal(string propName)
{
var type = this.GetType();
var propInfo = type.GetProperty(propName, BindingFlags.Instance);
if(propInfo == null)
throw new ArgumentException(String.Format(
"{0} is not a valid property of type: {1}",
propName,
type.FullName));
return propInfo.GetValue(this);
}
Keep in mind, though, that since you would already have access to the class and its properties (because you also have access to the method), it's much easier just to use the properties rather than do something fancy via Reflection.