[C#] How to Dynamically Get and Analyze Method Definitions

Using the Type.GetMethods method in C# Reflection allows you to retrieve an array containing information about all methods defined in a specific class or structure.

This is useful for investigating the functionality of external DLLs loaded in a plugin system or enumerating target methods in automated testing tools.

Here, I will explain an implementation example that uses BindingFlags to control the search scope while listing method names, return values, and parameter information.

目次

Implementing Method Retrieval and Analysis

The following sample code parses a sample class containing various types of methods (public/private, static/instance, overloads) and outputs their signatures (definition details) to the console.

Sample Code

using System;
using System.Linq;
using System.Reflection;
using System.Text;

public class Program
{
    public static void Main()
    {
        // 1. Get type information to analyze
        Type targetType = typeof(SampleService);

        Console.WriteLine($"Methods of Class: {targetType.Name}\n");

        // 2. Set search flags
        // Instance: Instance methods
        // Static: Static methods
        // Public: Public methods
        // NonPublic: Non-public methods (private, protected, etc.)
        // DeclaredOnly: Exclude inherited methods (like ToString)
        var flags = BindingFlags.Instance | 
                    BindingFlags.Static | 
                    BindingFlags.Public | 
                    BindingFlags.NonPublic | 
                    BindingFlags.DeclaredOnly;

        // 3. Get array of method information
        MethodInfo[] methods = targetType.GetMethods(flags);

        foreach (var m in methods)
        {
            // Build detailed method information into a string
            string accessibility = GetAccessibility(m);
            string returnType = m.ReturnType.Name;
            string methodName = m.Name;
            
            // Get parameter information
            ParameterInfo[] paramsInfo = m.GetParameters();
            string paramString = string.Join(", ", paramsInfo.Select(p => $"{p.ParameterType.Name} {p.Name}"));

            Console.WriteLine($"[{accessibility}] {returnType} {methodName}({paramString})");
        }
    }

    /// <summary>
    /// Helper to determine access modifier from MethodInfo
    /// </summary>
    static string GetAccessibility(MethodInfo m)
    {
        if (m.IsPublic) return "public";
        if (m.IsPrivate) return "private";
        if (m.IsFamily) return "protected";
        if (m.IsAssembly) return "internal";
        return "unknown";
    }
}

// Sample class to be analyzed
public class SampleService
{
    // Public Instance Method
    public void Connect(string url) { }

    // Overloaded Method
    public void Connect(string url, int timeout) { }

    // Method with Return Value
    public int CalculateStatus() => 200;

    // Static Method
    public static void ResetConfig() { }

    // Private Method
    private void InternalLog(string message) { }
}

Execution Result

Methods of Class: SampleService

[public] Void Connect(String url)
[public] Void Connect(String url, Int32 timeout)
[public] Int32 CalculateStatus()
[public] Void ResetConfig()
[private] Void InternalLog(String message)

Explanation and Technical Points

1. GetMethods Method and BindingFlags

Similar to Type.GetProperties, if you do not specify BindingFlags with GetMethods, it returns only “public instance and static methods” by default.

By specifying DeclaredOnly, you can exclude standard methods inherited from System.Object (such as ToString and Equals) and focus only on the implementation unique to that class.

2. Information Available from MethodInfo

You can access rich metadata from the retrieved MethodInfo object:

  • Name: The method name.
  • ReturnType: The return type (Type object). If it returns void, this will be System.Void.
  • GetParameters(): Retrieves the parameter list as an array of ParameterInfo. You can investigate parameter types, names, and default values from here.
  • IsPublic / IsStatic etc.: Properties to determine method attributes and modifiers.

3. Handling Overloads

Overloaded methods (methods with the same name but different arguments) are included in the array as separate MethodInfo objects. To identify a specific method uniquely, you need to check the types and number of arguments.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次