Gonzague Defraiteur
Gonzague Defraiteur

Reputation: 119

Check if a delegate is a method of an object, and retrieve this object reference, and method name

I want to know if this is possible given a delegate variable, to know if it is actually pointing to an object method, and to retrieve this object and the method's name.

e.g:

public delegate void test();
public static test testDel = null;
public void TestMethod()
{
    ;
}
public void TestDelegate()
{
    //here it is not a method of an object
    testDel += () => { };
    // here it is "TestMethod"
    testDel += this.TestMethod;
    // i want something like that:
    SomeDelegateInfoClass[] infos = testDel.GetAssignedObjectsAndMethodNames();
} 

Upvotes: 2

Views: 2228

Answers (1)

Evk
Evk

Reputation: 101473

Yes it's possible, delegate contains couple of properties just for that. First one is Target (target object) and second is Method (of type MethodInfo).

var target = testDel.Target; // null for static methods
var methodName = testDel.Method.Name;

Note however that in this case

testDel = () => { };

it's not true that this is "not a method of an object". Compiler will create new type and your empty anonymous function will be a method of that type. So

testDel = () => { };
var targetType = testDel.Target.GetType().Name; // will be something like <>c - name of compiler-generated type
var m = testDel.Method.Name; // will be something like <Main>b__2_0 - compiler generated name

Note also that if you add multiple methods to delegate, like this:

testDel += () => { };    
testDel += this.TestMethod;

Target and Method will contain information about last added method. To get information about all of them, you need to use GetInvocationList:

if (testDel != null) {
    foreach (var del in testDel.GetInvocationList()) {
       Console.WriteLine(del.Target);
       Console.WriteLine(del.Method);
    }
}

Upvotes: 4

Related Questions