2

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();
} 

1 Answer 1

4

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);
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.