Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Return a delegate given an object and a method name

Tags:

c#

reflection

Suppose I'm given an object and a string that holds a method name, how can I return a delegate to that method (of that method?) ?

Example:

MyDelegate GetByName(ISomeObject obj, string methodName)
{
    ...
    return new MyDelegate(...);
}

ISomeObject someObject = ...;
MyDelegate myDelegate = GetByName(someObject, "ToString");

//myDelegate would be someObject.ToString

Thanks in advance.

One more thing -- I really don't want to use a switch statement even though it would work but be a ton of code.

like image 499
Austin Salonen Avatar asked Apr 23 '09 19:04

Austin Salonen


Video Answer


1 Answers

You'll need to use Type.GetMethod to get the right method, and Delegate.CreateDelegate to convert the MethodInfo into a delegate. Full example:

using System;
using System.Reflection;

delegate string MyDelegate();

public class Dummy
{
    public override string ToString()
    {
        return "Hi there";
    }
}

public class Test
{
    static MyDelegate GetByName(object target, string methodName)
    {
        MethodInfo method = target.GetType()
            .GetMethod(methodName, 
                       BindingFlags.Public 
                       | BindingFlags.Instance 
                       | BindingFlags.FlattenHierarchy);

        // Insert appropriate check for method == null here

        return (MyDelegate) Delegate.CreateDelegate
            (typeof(MyDelegate), target, method);
    }

    static void Main()
    {
        Dummy dummy = new Dummy();
        MyDelegate del = GetByName(dummy, "ToString");

        Console.WriteLine(del());
    }
}

Mehrdad's comment is a great one though - if the exceptions thrown by this overload of Delegate.CreateDelegate are okay, you can simplify GetByName significantly:

    static MyDelegate GetByName(object target, string methodName)
    {
        return (MyDelegate) Delegate.CreateDelegate
            (typeof(MyDelegate), target, methodName);
    }

I've never used this myself, because I normally do other bits of checking after finding the MethodInfo explicitly - but where it's suitable, this is really handy :)

like image 87
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet