Multicast delegates

T

Tony Johansson

Hello!

Assume we have a delegate declaration like this
delegate double DoCalculate(double num);

I have read in some books that operators +, += ,- and -= can only be used
with multicast delegates, that is, delegates that return void.

I can use the delegate declared above with multicast using += but then only
the last added method will return.
So what is the reson for saying that multicast delegates can oly be used on
method that return void.
Is the reason that only the last added method will return the other methods
return values is gone.

//Tony
 
N

Nicholas Paldino [.NET/C# MVP]

Tony,

Well, you can use those operators to concatenate those delegate lists,
but it just doesn't make sense to if there is a return value, as you can't
get all the return values, only the last one.

What you could do is have the delegate take the previous result, then
iterate through the delegate list (you can call GetInvocationList on the
delegate to get the individual delegates) and pass the previous result to
the next delegate.
 
J

Jon Skeet [C# MVP]

Tony Johansson said:
Assume we have a delegate declaration like this
delegate double DoCalculate(double num);

I have read in some books that operators +, += ,- and -= can only be used
with multicast delegates, that is, delegates that return void.

Nope, that's wrong - both in the aspect of +=, -= etc, and the idea
that only delegates returning void are multicast delegates.
I can use the delegate declared above with multicast using += but then only
the last added method will return.
Yes.

So what is the reson for saying that multicast delegates can oly be used on
method that return void.

Simply an incorrect book, I suspect - or your memory is playing tricks
on you.
Is the reason that only the last added method will return the other methods
return values is gone.

That's a good reason to generally avoid having multiple actions on a
delegate which returns a value, but that's not the same thing as saying
you *can't* do it.

(Similarly, you don't have to use a delegate just with the Invoke()
method. You could get the invocation list, invoke each action in turn,
and gather together all the return values.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top