Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multicast Delegates must have a return type of void. Why?

Multicast Delegates must have a return type of void Otherwise it will throw an exception.

I want to know whats the reason behind it, what if multiple methods could have a same return type as of a delegate ?

like image 285
samj28 Avatar asked Sep 21 '12 12:09

samj28


People also ask

What should be the return type of multicast delegate method?

Multicast Delegates must have a return type of void Otherwise it will throw an exception.

What will happen if a delegate has a non void return type?

When the return type is not void as above in my case it is int. Methods with Int return types are added to the delegate instance and will be executed as per the addition sequence but the variable that is holding the return type value will have the value return from the method that is executed at the end.

What are the characteristics of multicast delegates?

The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined. The - operator can be used to remove a component delegate from a multicast delegate.

What are called multicast delegates?

A delegate that holds a reference to more than one method is called multicasting delegate.


1 Answers

The premise is wrong; it works fine:

Func<int> func = delegate { Console.WriteLine("first part"); return 5; };
func += delegate { Console.WriteLine("second part"); return 7; };
int result = func();

That is a multicast delegate with a non-void result, working fine. You can see from the console that both parts executed. The result of the last item is the one returned. We can demonstrate that this is a true multicast delegate:

if(func is MulticastDelegate) Console.WriteLine("I'm multicast");

and it will write "I'm multicast" even after just the first line (when there is only a single method listed).

If you need more control over individual results, then use GetInvocationList():

foreach (Func<int> part in func.GetInvocationList())
{
    int result = part();
}

which allows you to see each individual result.

In IL terminology:

.class public auto ansi sealed Func<+ TResult>
    extends System.MulticastDelegate`

which is to say: Func<T> inherits from MulticastDelegate. Basically, to all intents and purposes, all delegates in .NET are multicast delegates. You might be able to get a non-multicast delegate in managed C++, I don't know. But certainly not from C#.

like image 78
Marc Gravell Avatar answered Sep 18 '22 18:09

Marc Gravell