brian4342
brian4342

Reputation: 1253

How to get property information from a class

So I have a class;

public class person()
{
public string name {get; set;}
public int age {get; set;}
}

to find out the name of the properties in the class I can use the following method:

public void Check<T>(Expression<Func<T>> expr)
{
    var body = ((MemberExpression) expr.Body);
    string name = body.Member.Name;
}

So this would give me the 'age' in the string name

Check(() => person1.age);

How could I loop this so that I can pass in my initialized class and it return a list of the names of all the properties in the class. Currently my example only works for 1 but I may not know how many properties are in a class.

e.g. I would like to do something like this;

foreach( var property in person)
{
    Check(() => property);
}

And it would call the method for both the name and the age property in the person class.

Upvotes: 0

Views: 210

Answers (2)

bobthedeveloper
bobthedeveloper

Reputation: 3783

You can by using System.Reflection

Type type = person1.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(person1, null));
}

Upvotes: 1

Christos
Christos

Reputation: 53958

You can use Reflection in order to achieve this. Please look at the following code:

using System.Reflection;  

// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(person).GetProperties(BindingFlags.Public |
                                              BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
        delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
        { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });


foreach (PropertyInfo propertyInfo in propertyInfos)
{
    Console.WriteLine(propertyInfo.Name);
}

Upvotes: 2

Related Questions