System.Reflection.Type

Description

Retrieves all public and non-public methods defined on the current Type, including those inherited from base classes and implemented interfaces.

The GetMethods method returns an array of MethodInfo objects, each representing a method. You can then use these objects to inspect and invoke the methods.

Syntax

public MethodInfo[] GetMethods(
    BindingFlags bindingAttr
);

The syntax shown is for the C# language.

Parameters

bindingAttr
A bitmask comprised of one or more BindingFlags constants that specify how to search for members. This parameter can include flags like Public, NonPublic, Instance, Static, etc.

Return Value

An array of MethodInfo objects representing all public and non-public methods defined on the current Type. Returns an empty array if no methods match the specified binding flags.

Exceptions

This method does not throw exceptions.

Examples

Retrieving All Public Instance Methods

The following example retrieves all public instance methods defined on the String class.

using System;
using System.Reflection;

public class Example
{
    public static void Main()
    {
        Type stringType = typeof(String);

        MethodInfo[] methods = stringType.GetMethods(
            BindingFlags.Public | BindingFlags.Instance
        );

        Console.WriteLine("Public instance methods of String:");
        foreach (MethodInfo method in methods)
        {
            Console.WriteLine(method.Name);
        }
    }
}

Retrieving All Public and Non-Public Instance Methods

This example demonstrates how to retrieve both public and non-public instance methods.

using System;
using System.Reflection;

public class MyClass
{
    public void PublicMethod() { }
    private void PrivateMethod() { }
}

public class ReflectionExample
{
    public static void Main()
    {
        Type myClassType = typeof(MyClass);

        MethodInfo[] allMethods = myClassType.GetMethods(
            BindingFlags.Public |
            BindingFlags.NonPublic |
            BindingFlags.Instance
        );

        Console.WriteLine("All instance methods (public and private) of MyClass:");
        foreach (MethodInfo method in allMethods)
        {
            Console.WriteLine($"{method.Name} ({method.IsPublic ? "Public" : "NonPublic"})");
        }
    }
}