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:
Kindly assist me.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With