Get Property Names using Reflection [C#]
To get names of properties for a specific type use method Type.GetProperties. Method returns array of PropertyInfo objects and the property names are available through PropertyInfo.Name property. If you want to get only subset of all properties (e.g. only public static ones) use BindingFlags when calling GetProperties method. You have to specify at least two flags, one from Public/NonPublic and one of Instance/Static flags. If you use GetProperties without a BindingFlags parameter, default flags are Public + NonPublic + Instance.
Following example shows how to get public static properties.
[C#]using System.Reflection; // reflection namespace // get all public static properties of MyClass type PropertyInfo[] propertyInfos; propertyInfos = typeof(MyClass).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) { Console.WriteLine(propertyInfo.Name); }
See also
- [C#] Reflection Examples – examples how to use dynamically loaded assembly
- [C#] Get Method Names using Reflection – get method names of any class
- [C#] Get Calling Method using Reflection – how to get name of calling method
- [C#] Read-only PropertyGrid – how to add read-only functionality to PropertyGrid
- Type.GetProperties – MSDN – returns array of PropertyInfo objects
- PropertyInfo – MSDN – informations about the properties including property names
- BindingFlags – MSDN – enumeration to select specific properties (public, static, …)