views:

64

answers:

2

I have a Multiple target

Func<int,int,int> funHandler=Max;
funHandler+=square;

When i execute Console.WriteLine(funHandler(10,10)); it return the square of 10 (i.e) 200.It did not fire Max.

i used something like

 foreach(var v in funHandler.GetInvocationList())
 {
     Console.WriteLine(v(10,20));
 }

'V' is a variable,but it is used like a method.How can i fire all methods that is in delegate's invocation list?

+3  A: 

Well, may be Max has no side effects and you can't notice it? When you execute multicast delegate it returns result of only last delegate.

Try this:

Func<int, int, int> funHandler = (x, y) => { Console.WriteLine(x); return x; };
funHandler += (x, y) => { Console.WriteLine(y); return y; };
int res = funHandler(1, 2);
Console.WriteLine(res);

See? it works

To use invocation list do this:

foreach (var v in funHandler.GetInvocationList())
{
    ((Func<int, int, int>)v)(1, 2);
}

Or:

foreach (Func<int, int, int> v in funHandler.GetInvocationList())
{
    v(1, 2);
}
Andrey
Wouldn't `foreach (Func<int, int, int> v in funHandler.GetInvocationList()) { v(1,2); }` work as well? Looks cleaner IMHO.
Ruben
I think it would work. But I don't like hiding an explicit cast in foreach.
CodeInChaos
+1  A: 

Multicast with a delegate that returns something doesn't make much sense to me. I'd guess it executes all of them but discards all results but one.

CodeInChaos
+1. Indeed, it doesn't.
Hans Passant