Why delegates are declared as void mostly?

0 votes
asked Jul 14, 2013 in C#.NET by Venu

I have this question for long time in my mind but never got answer for this. In dotnet framework, almost, at least whatever the delegates I have seen, all are having no return value. Always the delegates are void. Why is it so? Is it not possible to return value from delegate?


1 Answer

+1 vote
answered Jul 15, 2013 by Aadhira (1,213 points)
selected Jul 15, 2013 by administrator
Best answer

Absolutely it is possible to return a value from delegate. In fact Func is a delegate that will accept parameters and return result. But, there is a problem with return value in delegate.

For example, if you look at the below code, we have a delegate that gets an integer and return a integer. The Main method is attached with 2 handlers in the same delegate. When you call the method GetValue(), it is calling all the handlers of that delegate. You run this application, you will get surprise because there will be one output and result would be 12.

Because, even if the delegate able to return value. if you have attached multiple handlers, then it will return the result only from the last attached handler.

public delegate int DelegateWithReturnValueHandler(int value);
public class DelegateWithReturnValueDemo
    public DelegateWithReturnValueHandler DelegateWithReturnValueHandler = null;
    public int GetValue(int value)
        return DelegateWithReturnValueHandler(value);

static void Main(string[] args)
    DelegateWithReturnValueDemo delegateWithReturnValueDemo = new DelegateWithReturnValueDemo();
    delegateWithReturnValueDemo.DelegateWithReturnValueHandler += (x) => x + 1;
    delegateWithReturnValueDemo.DelegateWithReturnValueHandler += (x) => x + 2;

Your answer


Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com