Use reflection to get the value of a property by name in a class instance

Posted by TheMoot on Stack Overflow See other posts from Stack Overflow or by TheMoot
Published on 2011-06-21T19:32:13Z Indexed on 2011/06/22 0:22 UTC
Read the original article Hit count: 124

Filed under:
|
|

Lets say I have

class Person
{
    public Person(int age, string name)
    {
        Age = age;
        Name = name; 
    }
    public int Age{get;set}
    public string Name{get;set}
}

and I would like to create a method that accepts a string that contains either "age" or "name" and returns an object with the value of that property.

Like the following pseudo code:

    public object GetVal(string propName)
    {
        return <propName>.value;  
    }

How can I do this using reflection?

I am coding using asp.net 3.5, c# 3.5

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET