Sometimes we come across a requirement to get list of methods in C# class. This is very useful if you want to automate your documentation process and want to have a list of methods in a class.
To get the list of methods in class you normally use the GetMethods method. This method will return an array of MethodInfo objects. We have a lot of information about a method in the MethodInfo object and the name is one of them.
Type.GetMethods
You can use BindingFlags to get a filtered list of methods. For example, if you want to get only Public methods in class you can write code like
MethodInfo[] mInfos = typeof(MyClass).GetMethods(BindingFlags.Public);
There are four types of binding flags
- Public
- Static
- NonPublic
- Instance
BindingFlags and MethodInfo enumerations are part of System.Reflaction namespace.
Example: Let’s assume you want to get the names of all public and static methods in a class.
MethodInfo[] mInfos = typeof(MyTestClass).GetMethods(BindingFlags.Public |
BindingFlags.Static);
Array.Sort(mInfos,
delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
{
return methodInfo1.Name.CompareTo(methodInfo2.Name);
});
Now let’s write names
foreach (MethodInfo mInfo in mInfos)
{
Console.WriteLine(mInfo.Name);
}