Use reflection to list a class’s methods in C#


This example uses the following code to add some simple methods to the Form1 class.

// Add some methods.
private void MyPrivateMethod(string arg0, string arg2) { }
public void MyPublicMethod(float float0, double double0) { }
private void MyOverloadedMethod() { }
private void MyOverloadedMethod(int arg0) { }
protected void MyProtectedMethod() { }

When the program’s form loads, the following code displays information about the class’s methods.

// List the methods.
// Use the class you want to study instead of Form1.
MethodInfo[] method_infos = typeof(Form1).GetMethods(
    BindingFlags.FlattenHierarchy |
    BindingFlags.Instance |
    BindingFlags.NonPublic |
    BindingFlags.Public |
foreach (MethodInfo info in method_infos)
    // Make a list of properties.
    string properties = "";
    if (info.IsConstructor) properties += " ctor";
    if (info.IsAbstract) properties += " abstract";
    if (info.IsPrivate) properties += " private";
    if (info.IsPublic) properties += " public";
    if (info.IsFamily) properties += " protected";
    if (info.IsFamilyAndAssembly)
        properties += " protected AND internal";
    if (info.IsFamilyOrAssembly)
        properties += " protected OR internal";
    if (info.IsFinal) properties += " sealed";
    if (info.IsGenericMethod) properties += " generic";
    if (info.IsStatic) properties += " static";
    if (info.IsVirtual) properties += " virtual";

    if (properties.Length > 0)
        properties = properties.Substring(1);

The code gets the Form1 type and calls its GetMethods method to get information about the class’s methods. See the example Use reflection to list a class’s properties in C# for information about the BindingFlags parameters.

The code then loops through the MethodInfo objects that GetMethods returns. The code checks a series of MethodInfo properties to get information about the field’s accessibility and builds a string describing the values.

The code finishes by calling the ListViewMakeRow method to display the information in the form’s ListView control. The MethodInfo object’s Name property gives the method’s name. The object’s ToString method returns the method with its signature as in Void MyOverloadedMethod(Int32).

Download the example program to see how the ListViewMakeRow method works and for other details.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in reflection and tagged , , , , , , , , , . Bookmark the permalink.