Get Method Names using Reflection [C#]
If you want to get method names of a given type in C#, you can use method Type.GetMethods. This method returns array of MethodInfo objects. MethodInfo contains many informations about the method and of course a method name (MethodInfo.Name). To filter returned methods (for example if you want to get only public static methods) use BindingFlags parameter when calling GetMethods method. Required are at least two flags, one from Public/NonPublic and one of Instance/Static flags. Of course you can use all four flags and also DeclaredOnly and FlattenHierarchy. BindingFlags enumeration and MethodInfo class are declared in System.Reflection namespace.
This example gets names of public static methods of MyClass, sorts them by name and writes them to console.
[C#]using System.Reflection; // get all public static methods of MyClass type MethodInfo[] methodInfos = typeof(MyClass).GetMethods(BindingFlags.Public | BindingFlags.Static); // sort methods by name Array.Sort(methodInfos, delegate(MethodInfo methodInfo1, MethodInfo methodInfo2) { return methodInfo1.Name.CompareTo(methodInfo2.Name); }); // write method names foreach (MethodInfo methodInfo in methodInfos) { Console.WriteLine(methodInfo.Name); }
See also
- [C#] Reflection Examples – examples how to use dynamically loaded assembly
- [C#] Get Property Names using Reflection – get property names of any class
- [C#] Get Calling Method using Reflection – how to get name of calling method
- [C#] Get Call Stack – how to write method names from call stack
- [C#] Read-only PropertyGrid – how to add read-only functionality to PropertyGrid
- Type.GetMethods – MSDN – returns array of MethodInfo objects
- MethodInfo – MSDN – informations about the methods including method names
- BindingFlags – MSDN – enumeration to filter specific methods (public, static, …)