Koda
Koda

Reputation: 1857

Delegate equality after casting

I am trying to cast a WaitCallBack into an Action<object>

I am doing this by:

WaitCallBack w1 = Foo;

Action<object> a1 = new Action<object>(w1);
Action<object> a2 = Foo;

However, when i try to compare the a1 with a2, it will return false.

Is there away to cast the delegates, so that the equality will be true?

Thanks.

Upvotes: 1

Views: 123

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

Delegates compare by method+target; the problem is that you are comparing different things!

Perhaps it becomes clearer if we expand this line to what the compiler sees:

Action<object> a1 = new Action<object>(w1);

is actually:

Action<object> a1 = new Action<object>(w1.Invoke);

(using the implicit Invoke operation on a delegate)

You you can see that the target is w1, and the method is Invoke. We can confirm this:

Console.WriteLine(a1.Method.Name); // Invoke
Console.WriteLine(ReferenceEquals(a1.Target, w1)); // true

Compare to the other:

Action<object> a2 = Foo;

Here, the target is either null (if static) or this (if non-static), and the method is Foo. The delegates are not the same. It is correct that it reports false.

You can check this chained operation manually, but it is a bit tedious, especially if you need to consider every combination/depth; but a trivial example:

Delegate del = a1.Target as Delegate;
if(del != null)
{
    if(del.Method == a2.Method && del.Target == a2.Target)
    {
        Console.WriteLine("pass");
    }
}

Upvotes: 1

Related Questions