Edit

Share via


Type.GetMethod Method

Definition

Gets a specific method of the current Type.

Overloads

GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified generic parameter count, argument types and modifiers, using the specified binding constraints and the specified calling convention.

GetMethod(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified generic parameter count, argument types and modifiers, using the specified binding constraints.

GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.

GetMethod(String, Int32, Type[], ParameterModifier[])

Searches for the specified public method whose parameters match the specified generic parameter count, argument types and modifiers.

GetMethod(String, Int32, BindingFlags, Type[])

Searches for the specified method whose parameters match the specified generic parameter count and argument types, using the specified binding constraints.

GetMethod(String, BindingFlags)

Searches for the specified method, using the specified binding constraints.

GetMethod(String, BindingFlags, Type[])

Searches for the specified method whose parameters match the specified argument types, using the specified binding constraints.

GetMethod(String, Int32, Type[])

Searches for the specified public method whose parameters match the specified generic parameter count and argument types.

GetMethod(String, Type[])

Searches for the specified public method whose parameters match the specified argument types.

GetMethod(String)

Searches for the public method with the specified name.

GetMethod(String, Type[], ParameterModifier[])

Searches for the specified public method whose parameters match the specified argument types and modifiers.

GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified method whose parameters match the specified generic parameter count, argument types and modifiers, using the specified binding constraints and the specified calling convention.

C#
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
C#
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);

Parameters

name
String

The string containing the name of the public method to get.

genericParameterCount
Int32

The number of generic type parameters of the method.

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted.

-or-

Default to return null.

binder
Binder

An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder.

callConvention
CallingConventions

The object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and how the stack is cleaned up.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. To be only used when calling through COM interop, and only parameters that are passed by reference are handled. The default binder does not process this parameter.

Returns

An object representing the method that matches the specified generic parameter count, argument types, modifiers, binding constraints and calling convention, if found; otherwise, null.

Exceptions

name is null.

-or-

types is null.

-or-

One of the elements in the types array is null.

genericParameterCount is negative.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

GetMethod(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

C#
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
C#
public System.Reflection.MethodInfo GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers);

Parameters

name
String

The string containing the name of the method to get.

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted.

-or-

Default to return null.

binder
Binder

An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder.

callConvention
CallingConventions

The object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and how the stack is cleaned up.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. To be only used when calling through COM interop, and only parameters that are passed by reference are handled. The default binder does not process this parameter.

Returns

An object representing the method that matches the specified requirements, if found; otherwise, null.

Implements

Exceptions

More than one method is found with the specified name and matching the specified binding constraints.

name is null.

-or-

types is null.

-or-

One of the elements in types is null.

types is multidimensional.

-or-

modifiers is multidimensional.

Examples

The following example finds specific overloads of MethodA, specifying binding constraints, calling conventions, and a variety of argument types.

Note

The Visual C# 2005 example requires the /unsafe compiler option.

C#

using System;
using System.Reflection;

class Program3
{
    // Methods to get:

    public void MethodA(int i, int j) { }

    public void MethodA(int[] i) { }

    public unsafe void MethodA(int* i) { }

    public void MethodA(ref int r) {}

    // Method that takes an out parameter:
    public void MethodA(int i, out int o) { o = 100;}

  static void Main(string[] args)
  {
    MethodInfo mInfo;

    // Get MethodA(int i, int j)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int), typeof(int) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int[] i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int[]) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int* i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int).MakePointerType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(ref int r)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int i, out int o)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        CallingConventions.Any,
        new Type[] { typeof(int), typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);
  }
}

Remarks

Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

The following table shows what members of a base class are returned by the GetXXX methods when reflecting on a type.

Member Type Static Non-Static
Constructor No No
Field No Yes. A field is always hide-by-name-and-signature.
Event Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
Method No Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
Nested Type No No
Property Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.

  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. Custom attributes are not part of the common type system.

The following BindingFlags filter flags can be used to define which methods to include in the search:

  • You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • Specify BindingFlags.Public to include public methods in the search.

  • Specify BindingFlags.NonPublic to include nonpublic methods (that is, private, internal, and protected methods) in the search.

  • Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly to search only the methods declared on the Type, not methods that were simply inherited.

See System.Reflection.BindingFlags for more information.

Note

You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.

If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

Note

For generic methods, do not include the type arguments in name. For example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified method whose parameters match the specified generic parameter count, argument types and modifiers, using the specified binding constraints.

C#
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
C#
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);

Parameters

name
String

The string containing the name of the public method to get.

genericParameterCount
Int32

The number of generic type parameters of the method.

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted.

-or-

Default to return null.

binder
Binder

An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. To be only used when calling through COM interop, and only parameters that are passed by reference are handled. The default binder does not process this parameter.

Returns

An object representing the method that matches the specified generic parameter count, argument types, modifiers and binding constraints, if found; otherwise, null.

Exceptions

name is null.

-or-

types is null.

-or-

One of the elements in the types array is null.

genericParameterCount is negative.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.

C#
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
C#
public System.Reflection.MethodInfo GetMethod(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type[] types, System.Reflection.ParameterModifier[] modifiers);

Parameters

name
String

The string containing the name of the method to get.

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted.

-or-

Default to return null.

binder
Binder

An object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.

-or-

A null reference (Nothing in Visual Basic), to use the DefaultBinder.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. To be only used when calling through COM interop, and only parameters that are passed by reference are handled. The default binder does not process this parameter.

Returns

An object representing the method that matches the specified requirements, if found; otherwise, null.

Implements

Exceptions

More than one method is found with the specified name and matching the specified binding constraints.

name is null.

-or-

types is null.

-or-

One of the elements in types is null.

types is multidimensional.

-or-

modifiers is multidimensional.

Examples

The following example finds specific overloads of MethodA, specifying binding constraints and a variety of argument types.

Note

The Visual C# 2005 example requires the /unsafe compiler option.

C#

using System;
using System.Reflection;

class Program5
{
    // Methods to get:

    public void MethodA(int i, int j) { }

    public void MethodA(int[] i) { }

    public unsafe void MethodA(int* i) { }

    public void MethodA(ref int r) {}

    // Method that takes an out parameter.
    public void MethodA(int i, out int o) { o = 100; }

  static void Main(string[] args)
  {
    MethodInfo mInfo;

    // Get MethodA(int i, int j)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int), typeof(int) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int[] i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int[]) },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int* i)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int).MakePointerType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(ref int r)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int i, out int o)
    mInfo = typeof(Program).GetMethod("MethodA",
        BindingFlags.Public | BindingFlags.Instance,
        null,
        new Type[] { typeof(int), typeof(int).MakeByRefType() },
        null);
    Console.WriteLine("Found method: {0}", mInfo);
  }
}

Remarks

Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

The following BindingFlags filter flags can be used to define which methods to include in the search:

  • You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

  • Specify BindingFlags.Public to include public methods in the search.

  • Specify BindingFlags.NonPublic to include nonpublic methods (that is, private, internal, and protected methods) in the search.

  • Specify BindingFlags.FlattenHierarchy to include public and protected static members up the hierarchy; private static members in inherited classes are not included.

The following BindingFlags modifier flags can be used to change how the search works:

  • BindingFlags.IgnoreCase to ignore the case of name.

  • BindingFlags.DeclaredOnly to search only the methods declared on the Type, not methods that were simply inherited.

See System.Reflection.BindingFlags for more information.

Note

You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.

If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

Note

For generic methods, do not include the type arguments in name. For example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetMethod(String, Int32, Type[], ParameterModifier[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified public method whose parameters match the specified generic parameter count, argument types and modifiers.

C#
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
C#
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, Type[] types, System.Reflection.ParameterModifier[] modifiers);

Parameters

name
String

The string containing the name of the public method to get.

genericParameterCount
Int32

The number of generic type parameters of the method.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. To be only used when calling through COM interop, and only parameters that are passed by reference are handled. The default binder does not process this parameter.

Returns

An object representing the public method that matches the specified generic parameter count, argument types and modifiers, if found; otherwise, null.

Exceptions

name is null.

-or-

types is null.

-or-

One of the elements in the types array is null.

genericParameterCount is negative.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

GetMethod(String, Int32, BindingFlags, Type[])

Source:
Type.cs

Searches for the specified method whose parameters match the specified generic parameter count and argument types, using the specified binding constraints.

C#
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, Type[] types);

Parameters

name
String

The string containing the name of the method to get.

genericParameterCount
Int32

The number of generic type parameters of the method.

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted.

-or-

Default to return null.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

Returns

An object representing the method that matches the specified generic parameter count, argument types, and binding constraints, if found; otherwise, null.

Applies to

.NET 9
Product Versions
.NET 9

GetMethod(String, BindingFlags)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified method, using the specified binding constraints.

C#
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr);
C#
public System.Reflection.MethodInfo GetMethod(string name, System.Reflection.BindingFlags bindingAttr);

Parameters

name
String

The string containing the name of the method to get.

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted.

-or-

Default to return null.

Returns

An object representing the method that matches the specified requirements, if found; otherwise, null.

Implements

Exceptions

More than one method is found with the specified name and matching the specified binding constraints.

name is null.

Examples

The following example gets the method that matches the specified binding flags.

C#
using System;
using System.Reflection;

class Program2
{
    // Method to get:
    public void MethodA() { }

    static void Main(string[] args)
    {
        // Get MethodA()
        MethodInfo mInfo = typeof(Program).GetMethod("MethodA",
            BindingFlags.Public | BindingFlags.Instance);
        Console.WriteLine("Found method: {0}", mInfo);
    }
}

Remarks

The following BindingFlags filter flags can be used to define which methods to include in the search:

The following BindingFlags modifier flags can be used to change how the search works:

See System.Reflection.BindingFlags for more information.

If a method is overloaded and more than one overload meets the constraints specified by the bindingAttr argument, the method throws an AmbiguousMatchException exception. In the following example, an exception is thrown because:

  • The TestClass type has two public instance overloads of the DisplayValue method, DisplayValue(String) and DisplayValue(String, Object[]).

  • The TestClass type has two public instance overloads of the Equals method, one of which is inherited from Object: Equals(TestClass) and Equals(Object).

C#
using System;
using System.Reflection;

public class TestClass
{
    public void DisplayValue(String s)
    {
        Console.WriteLine(s);
    }

    public void DisplayValue(String s, params Object[] values)
    {
        Console.WriteLine(s, values);
    }

    public static bool Equals(TestClass t1, TestClass t2)
    {
        return Object.ReferenceEquals(t1, t2);
    }

    public bool Equals(TestClass t)
    {
        return Object.ReferenceEquals(this, t);
    }
}

public class Example1
{
    public static void Main()
    {
        Type t = typeof(TestClass);

        RetrieveMethod(t, "DisplayValue", BindingFlags.Public | BindingFlags.Instance);

        RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Instance);

        RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

        RetrieveMethod(t, "Equals", BindingFlags.Public | BindingFlags.Static);
    }

    private static void RetrieveMethod(Type t, String name, BindingFlags flags)
    {
        try
        {
            MethodInfo m = t.GetMethod(name, flags);
            if (m != null)
            {
                Console.Write("{0}.{1}(", t.Name, m.Name);
                ParameterInfo[] parms = m.GetParameters();
                for (int ctr = 0; ctr < parms.Length; ctr++)
                {
                    Console.Write(parms[ctr].ParameterType.Name);
                    if (ctr < parms.Length - 1)
                        Console.Write(", ");
                }
                Console.WriteLine(")");
            }
            else
            {
                Console.WriteLine("Method not found");
            }
        }
        catch (AmbiguousMatchException)
        {
            Console.WriteLine("The following duplicate matches were found:");
            MethodInfo[] methods = t.GetMethods(flags);
            foreach (var method in methods)
            {
                if (method.Name != name) continue;

                Console.Write("   {0}.{1}(", t.Name, method.Name);
                ParameterInfo[] parms = method.GetParameters();
                for (int ctr = 0; ctr < parms.Length; ctr++)
                {
                    Console.Write(parms[ctr].ParameterType.Name);
                    if (ctr < parms.Length - 1)
                        Console.Write(", ");
                }
                Console.WriteLine(")");
            }
        }
        Console.WriteLine();
    }
}
// The example displays the following output:
//       The following duplicate matches were found:
//          TestClass.DisplayValue(String)
//          TestClass.DisplayValue(String, Object[])
//       
//       The following duplicate matches were found:
//          TestClass.Equals(TestClass)
//          TestClass.Equals(Object)
//       
//       TestClass.Equals(TestClass)
//       
//       TestClass.Equals(TestClass, TestClass)

You can do one of the following to retrieve a specific method:

  • Change the binding constraints. In the previous example, attempting to retrieve a public instance Equals method that is declared by the type and not inherited successfully retrieves Equals(TestClass).

  • Call an overload of the GetMethod method that includes a types parameter which defines the types of the method's parameters.

  • Call the GetMethods(BindingFlags) method to retrieve an array containing all of the methods belonging to a type that have the specified binding attributes. You can then iterate it to identify the duplicate methods named name. This approach is illustrated in the previous example's handler for the AmbiguousMatchException exception.

If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

Note

For generic methods, do not include the type arguments in name. For example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetMethod(String, BindingFlags, Type[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified method whose parameters match the specified argument types, using the specified binding constraints.

C#
public System.Reflection.MethodInfo? GetMethod(string name, System.Reflection.BindingFlags bindingAttr, Type[] types);

Parameters

name
String

The string containing the name of the method to get.

bindingAttr
BindingFlags

A bitwise combination of the enumeration values that specify how the search is conducted. -or- Default to return null.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get. -or- An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

Returns

An object representing the method that matches the specified requirements, if found; otherwise, null.

Applies to

.NET 9 and other versions
Product Versions
.NET 6, 7, 8, 9

GetMethod(String, Int32, Type[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified public method whose parameters match the specified generic parameter count and argument types.

C#
public System.Reflection.MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types);
C#
public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, Type[] types);

Parameters

name
String

The string containing the name of the public method to get.

genericParameterCount
Int32

The number of generic type parameters of the method.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

Returns

An object representing the public method whose parameters match the specified generic parameter count and argument types, if found; otherwise, null.

Exceptions

name is null.

-or-

types is null.

-or-

One of the elements in the types array is null.

genericParameterCount is negative.

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

GetMethod(String, Type[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified public method whose parameters match the specified argument types.

C#
public System.Reflection.MethodInfo? GetMethod(string name, Type[] types);
C#
public System.Reflection.MethodInfo GetMethod(string name, Type[] types);

Parameters

name
String

The string containing the name of the public method to get.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

Returns

An object representing the public method whose parameters match the specified argument types, if found; otherwise, null.

Implements

Exceptions

More than one method is found with the specified name and specified parameters.

name is null.

-or-

types is null.

-or-

One of the elements in types is null.

types is multidimensional.

Examples

The following example finds specific overloads of MethodA, specifying a variety of argument types.

Note

The Visual C# 2005 example requires the /unsafe compiler option.

C#

using System;
using System.Reflection;

class Program4
{
    // Methods to get:

    public void MethodA(int i, int j) { }

    public void MethodA(int[] i) { }

    public unsafe void MethodA(int* i) { }

    public void MethodA(ref int r) {}

    // Method that takes an out parameter:
    public void MethodA(int i, out int o) { o = 100;}

  static void Main(string[] args)
  {
    MethodInfo mInfo;

    // Get MethodA(int i, int i)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int), typeof(int) });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int[] i)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int[]) });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int* i)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int).MakePointerType() });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(ref int r)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int).MakeByRefType() });
    Console.WriteLine("Found method: {0}", mInfo);

    // Get MethodA(int i, out int o)
    mInfo = typeof(Program).GetMethod("MethodA",
        new Type[] { typeof(int), typeof(int).MakeByRefType() });
    Console.WriteLine("Found method: {0}", mInfo);
  }
}

The following example retrieves MethodInfo objects that represent the Add methods of a non-generic type (the ArrayList class), an open generic type (the List<T> class), and a closed generic type (the List(Of String) type.

C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

public class Example
{
   public static void Main()
   {
      // Get a Type object that represents a non-generic type.
      GetAddMethod(typeof(ArrayList));

      var list = new List<String>();
      // Get a Type object that represents a constructed generic type.
      Type closed = list.GetType();
      GetAddMethod(closed);
      
      // Get a Type object that represents an open generic type.
      Type open = typeof(List<>);
      GetAddMethod(open);
   }

   private static void GetAddMethod(Type typ)
   {
      MethodInfo method;
      // Determine if this is a generic type.
      if (typ.IsGenericType) {
         // Is it an open generic type?
         if (typ.ContainsGenericParameters)
            method = typ.GetMethod("Add", typ.GetGenericArguments());
         // Get closed generic type arguments.
         else
            method = typ.GetMethod("Add", typ.GenericTypeArguments);
      }
      // This is not a generic type.
      else {
         method = typ.GetMethod("Add", new Type[] { typeof(Object) } );
      }

      // Test if an Add method was found.
      if (method == null) { 
         Console.WriteLine("No Add method found.");
         return;
      }   
      
      Type t = method.ReflectedType;
      Console.Write("{0}.{1}.{2}(", t.Namespace, t.Name, method.Name);
      ParameterInfo[] parms = method.GetParameters();
      for (int ctr = 0; ctr < parms.Length; ctr++)
         Console.Write("{0}{1}", parms[ctr].ParameterType.Name, 
                       ctr < parms.Length - 1 ? ", " : "");

      Console.WriteLine(")");
   }   
}
// The example displays the following output:
//       System.Collections.ArrayList.Add(Object)
//       System.Collections.Generic.List`1.Add(String)
//       System.Collections.Generic.List`1.Add(T)

The example defines a GetAddMethod method that retrieves the appropriate MethodInfo object. To provide the types argument for an open generic type, it calls the Type.GetGenericArguments method. To provide the types argument for a closed generic type, it retrieves the value of the Type.GenericTypeArguments property.

Remarks

The search for name is case-sensitive. The search includes public static and public instance methods.

Note

You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.

If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

Note

The name parameter cannot include type arguments. For example, the C# code GetMethod("MyGenericMethod<int>") searches for a method with the text name "MyGenericMethod<int>", rather than for a method named MyGenericMethod that has one generic argument of type int. Instead, use GetMethod("MyGenericMethod") with the appropriate parameter in the types array.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetMethod(String)

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the public method with the specified name.

C#
public System.Reflection.MethodInfo? GetMethod(string name);
C#
public System.Reflection.MethodInfo GetMethod(string name);

Parameters

name
String

The string containing the name of the public method to get.

Returns

An object that represents the public method with the specified name, if found; otherwise, null.

Implements

Exceptions

More than one method is found with the specified name.

name is null.

Examples

The following example gets a method named MethodA.

C#

using System;
using System.Reflection;

class Program
{

    // Method to get:
    public void MethodA() { }

    static void Main(string[] args)
    {

        // Get MethodA()
        MethodInfo mInfo = typeof(Program).GetMethod("MethodA");
        Console.WriteLine("Found method: {0}", mInfo);
    }
}

Remarks

The search for name is case-sensitive. The search includes public static and public instance methods.

If a method is overloaded and has more than one public method, the GetMethod(String) method throws an AmbiguousMatchException exception. In the following example, an exception is thrown because there is more than one public overload of the Int32.ToString method. On the other hand, because the Person.ToString method overrides Object.ToString and therefore is not overloaded, the GetMethod(String) method is able to retrieve the MethodInfo object.

C#
using System;
using System.Reflection;

public class Person
{
    public String FirstName;
    public String LastName;

    public override String ToString()
    {
        return (FirstName + " " + LastName).Trim();
    }
}

public class Example2
{
    public static void Main()
    {
        Type t = typeof(Person);
        RetrieveMethod(t, "ToString");

        t = typeof(Int32);
        RetrieveMethod(t, "ToString");
    }

    private static void RetrieveMethod(Type t, String name)
    {
        try
        {
            MethodInfo m = t.GetMethod(name);
            if (m != null)
                Console.WriteLine("{0}.{1}: {2} method", m.ReflectedType.Name,
                                  m.Name, m.IsStatic ? "Static" : "Instance");
            else
                Console.WriteLine("{0}.ToString method not found", t.Name);
        }
        catch (AmbiguousMatchException)
        {
            Console.WriteLine("{0}.{1} has multiple public overloads.",
                              t.Name, name);
        }
    }
}
// The example displays the following output:
//       Person.ToString: Instance method
//       Int32.ToString has multiple public overloads.

You can do one of the following to retrieve a specific method:

  • Call the GetMethod(String, BindingFlags) method and specify a bindingAttr argument that uniquely identifies the method. For example, if the exception is thrown because a type has a static and an instance overload, you can specify a bindingAttr argument of BindingFlags.InstanceOrBindingFlags.Instance.

  • Call an overload of the GetMethod method that includes a types parameter which defines the types of the method's parameters.

  • Call the GetMethods() method to retrieve an array containing all of the public methods belonging to a type. You can then iterate it to identify the duplicate methods named name.

If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

Note

For generic methods, do not include the type arguments in name. For example, the C# code GetMember("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetMethod(String, Type[], ParameterModifier[])

Source:
Type.cs
Source:
Type.cs
Source:
Type.cs

Searches for the specified public method whose parameters match the specified argument types and modifiers.

C#
public System.Reflection.MethodInfo? GetMethod(string name, Type[] types, System.Reflection.ParameterModifier[]? modifiers);
C#
public System.Reflection.MethodInfo GetMethod(string name, Type[] types, System.Reflection.ParameterModifier[] modifiers);

Parameters

name
String

The string containing the name of the public method to get.

types
Type[]

An array of Type objects representing the number, order, and type of the parameters for the method to get.

-or-

An empty array of Type objects (as provided by the EmptyTypes field) to get a method that takes no parameters.

modifiers
ParameterModifier[]

An array of ParameterModifier objects representing the attributes associated with the corresponding element in the types array. To be only used when calling through COM interop, and only parameters that are passed by reference are handled. The default binder does not process this parameter.

Returns

An object representing the public method that matches the specified requirements, if found; otherwise, null.

Implements

Exceptions

More than one method is found with the specified name and specified parameters.

name is null.

-or-

types is null.

-or-

One of the elements in types is null.

types is multidimensional.

-or-

modifiers is multidimensional.

Remarks

Although the default binder does not process ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.

The search for name is case-sensitive. The search includes public static and public instance methods.

Note

You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.

If the current Type represents a constructed generic type, this method returns the MethodInfo with the type parameters replaced by the appropriate type arguments.

If the current Type represents a type parameter in the definition of a generic type or generic method, this method searches the methods of the class constraint, or the methods of Object if there is no class constraint.

Note

For generic methods, do not include the type arguments in name. For example, the C# code GetMethod("MyMethod<int>") searches for a member with the text name "MyMethod<int>", rather than for a method named MyMethod that has one generic argument of type int. Instead, use GetMethod("MyMethod") with the appropriate parameter in the types array.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1