Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

How to Get Methods with C# Reflection

Learn how to retrieve method metadata with C# reflection, use BindingFlags to filter results, resolve overloads, and cache MethodInfo for better performance.

~4 min readC#
#Reflection#MethodInfo#Type Inspection#Runtime Metadata
A magnifying glass over a C# class diagram highlighting method names, representing reflection retrieving methods at runtime.

When you need to inspect the methods of a type at runtime, reflection is the standard way to do it. The System.Type class exposes two primary APIs: GetMethods() returns an array of matching MethodInfo objects, while GetMethod(string name) finds a single method by name. The returned MethodInfo type is part of System.Reflection and gives you access to metadata such as parameters, return types, and custom attributes without knowing the type at compile time.

The Core API for Retrieving Methods

The simplest call is typeof(MyClass).GetMethods(), which returns all public instance and static methods available on the type, including inherited public methods. For a more controlled search, GetMethod(string name) returns a public method with that name, but it throws AmbiguousMatchException if multiple overloads match. To avoid that, provide parameter types or use GetMethods() and filter manually.

csharp
using System; using System.Reflection; public class Sample { public void DoWork() { } public void DoWork(int value) { } private void Helper() { } } Type type = typeof(Sample); MethodInfo[] allPublic = type.GetMethods(); foreach (var method in allPublic) { Console.WriteLine(method.Name); }

This code prints DoWork, DoWork, ToString, Equals, GetHashCode, and GetType because GetMethods() without flags includes inherited public methods. The private Helper is not included. If you need only methods declared on the type itself, combine BindingFlags.DeclaredOnly with the visibility and instance/static flags you want.

Filtering Methods with BindingFlags

BindingFlags gives you precise control over which methods are returned. The most common combinations are:

  • BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static – the default when you call GetMethods() with no flags.
  • BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static – to include private, protected, and internal methods.
  • BindingFlags.DeclaredOnly – to exclude inherited members.

For example, to get only private instance methods declared on the type:

csharp
MethodInfo[] privateMethods = type.GetMethods( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

This returns only Helper. Remember that with BindingFlags, you need to specify Instance or Static explicitly; otherwise, no methods are returned. A common mistake is to pass only Public without Instance or Static, which results in an empty array.

Working with MethodInfo: Invocation and Metadata

Once you have a MethodInfo, you can inspect its parameters, return type, and attributes, or invoke it. Invocation is done with Invoke(object obj, object[] parameters), where obj is the target instance for instance methods or null for static methods. The parameters array must match the method signature.

csharp
MethodInfo method = type.GetMethod("DoWork", new[] { typeof(int) }); object instance = Activator.CreateInstance(type); method.Invoke(instance, new object[] { 42 });

For non-generic overloads, passing a parameter type array to GetMethod resolves the overload unambiguously. This is safer than calling GetMethod("DoWork") alone, which can throw if multiple overloads exist. The returned MethodInfo also exposes ReturnType, GetParameters(), and GetCustomAttributes(), which are useful for building tools like serializers or dependency injection containers.

Performance and Caching Considerations

Reflection is significantly slower than direct method calls because it involves metadata lookup, argument array allocation, and runtime type checks. In hot paths, repeated calls to GetMethods() or GetMethod() can become a bottleneck. The typical mitigation is to cache the MethodInfo objects after the first lookup. For example, a static dictionary keyed by type and method name can store the resolved MethodInfo for reuse.

csharp
private static readonly Dictionary<string, MethodInfo> Cache = new(); public static MethodInfo GetCachedMethod(Type type, string name) { string key = type.FullName + "." + name; if (!Cache.TryGetValue(key, out var method)) { method = type.GetMethod(name); Cache[key] = method; } return method; }

This simple cache assumes a unique method name. If you need to cache overloads, include the parameter types in the key. If the cache is shared across threads, use ConcurrentDictionary or synchronize access.

Even with caching, invoking a MethodInfo remains slower than calling a delegate. If you need repeated invocation, consider converting the MethodInfo to a strongly typed delegate with Delegate.CreateDelegate or by building an expression tree. This moves the reflection cost to the setup phase and gives you near-direct call performance afterward.

Handling Overloads and Generic Methods

Overload resolution is a common source of confusion. GetMethod(string name) throws AmbiguousMatchException when multiple methods share the name. To select a specific overload, pass an array of parameter types, as shown earlier. For generic methods, the situation is more complex. GetMethod("MyGeneric") returns the open generic method definition, not a constructed version. To get a closed generic method, call MakeGenericMethod with the desired type arguments.

csharp
MethodInfo openMethod = typeof(GenericSample).GetMethod("Process"); MethodInfo closedMethod = openMethod.MakeGenericMethod(typeof(string));

This assumes the type has a uniquely named Process method. If there are multiple Process overloads, use the same parameter-type or filtering approach to isolate the one you want. If you need to find a generic method with specific constraints, you may have to iterate over all methods and check IsGenericMethodDefinition and GetGenericArguments().

Common Pitfalls and Edge Cases

Several edge cases can trip up even experienced developers. First, GetMethods() does not guarantee the order of the returned array, so do not rely on it. Second, inherited methods are included by default, which can cause unexpected results when you filter by name. Use DeclaredOnly to restrict results to the type itself. Third, GetMethod can return null if no matching method exists, so always check for null before invoking. Finally, invoking non-public methods may be restricted by runtime security policy; on .NET Framework partial-trust environments this can require full trust, while .NET Core and later are generally more permissive.

Another subtle issue is that GetMethods() includes interface methods only when they are visible as public methods on the type. Explicit interface implementations are private and require the NonPublic flag to retrieve.

When to Use Reflection vs. Alternatives

Reflection is the right tool when you need runtime type discovery that cannot be done at compile time, such as building a plugin system, a serializer, or an ORM. However, if you know the method signature at compile time, prefer a delegate or an interface. For scenarios where you need to invoke a method by name but the set of methods is fixed, consider using a Dictionary<string, Delegate> to map names to delegates, avoiding reflection entirely.

Use GetMethods() when you need to enumerate all methods for analysis, such as in a documentation generator. Use GetMethod() when you need a single known method and can provide parameter types to avoid ambiguity. The decision ultimately depends on whether the type is known at compile time and whether the overhead of reflection is acceptable for your performance requirements.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.