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

Viewed 6976

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.

1 Answers
Related