Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get List of Properties from a Class T using C# Reflection

I need to get a list of properties from Class T - GetProperty<Foo>(). I tried the following code but it fails.

Sample Class:

public class Foo {
    public int PropA { get; set; }
    public string PropB { get; set; }
}

I tried the following Code:

public List<string> GetProperty<T>() where T : class {

    List<string> propList = new List<string>();

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

    // write property names
    foreach (PropertyInfo propertyInfo in propertyInfos) {
        propList.Add(propertyInfo.Name);
    }

    return propList;
}

I need to get the List of property name

Expected output: GetProperty<Foo>()

new List<string>() {
    "PropA",
    "PropB"
}

I tried lot of stackoverlow reference, but I can't able to get the expected output.

Reference:

  1. c# getting ALL the properties of an object
  2. How to get the list of properties of a class?

Kindly assist me.

like image 783
B.Balamanigandan Avatar asked Feb 05 '23 08:02

B.Balamanigandan


1 Answers

Your binding flags are incorrect.

Since your properties are not static properties but rather instance properties, you need to replace BindingFlags.Static with BindingFlags.Instance.

propertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

This will appropriately look for public, instance, non-static properties on your type. You can also omit the binding flags entirely and get the same results in this case.

like image 103
David L Avatar answered Feb 08 '23 15:02

David L