Get the list of method names from the C# class

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);
}

About the author

Naveed Ul-Haq

I am a UK-based Technical Architect, Founder & Technology Evangelist. I'm Optimizely MVP & Optimizely SME on Content Cloud and Commerce Cloud. I love working on .NET-based CMS, eCommerce solutions, .NET Core, DevOps, and Cloud computing. I'm also a Certified Optimizely Content Cloud Developer, Certified Optimizely Commerce Cloud developer, Optimizely B2B Commerce developer and Microsoft Certified Professional in Azure application development. I spend my free time with my family and reading books. You can contact me at hello@naveedulhaq.com

View all posts

Leave a Reply

Your email address will not be published.