What is the return type for an Event in .NET?
Solution 1
It depends on the type of the delegate you declare the event with. "Typical" events are declared with a delegate of type EventHandler
or EventHandler<TEventArgs>
which returns void
, but nothing forbids declaring an event with a different type of delegate... if not the Principle Of Least Surprise (POLS).
"Typical":
public event EventHandler MyVoidEvent;
"Custom":
public delegate bool MyBoolDelegate(object sender, EventArgs e);
public event MyBoolDelegate MyBoolEvent;
Normally you would put "return values" in the EventArgs
object, that's why events don't need to return values... but they can if they're told to.
Solution 2
By default most event handlers return void, however, it is possible for handlers to return values.
You can refer this article for further reference: http://blogs.msdn.com/b/deviations/archive/2008/11/27/event-handlers-returning-values.aspx
Related videos on Youtube
Tab
Updated on September 16, 2022Comments
-
Tab over 1 year
I would like know what's the default return type for an Event: somebody says Event has not return type; others says Event has return type. Thanks.
-
Amit Singh almost 11 yearsits void...you can see where you define event.....
-
Rao Ehsan almost 11 yearsEvent is object and object doesn't return anything, I think you're asking about event handler..!!
-
-
Matthew Watson almost 11 yearsNote the difference between an
event
and anEventHandler
-
Jeppe Stig Nielsen almost 11 yearsGood answer. With events, usually, it is intended that many different agents could "subscribe" to the same event, each of them calling the (implicit)
add
accessor of the event. The underlying delegate field therefore contains a multicast delegate. Then multicast delegates with return types different fromvoid
work by returning the output from the last method on the invocation list of that multicast delegate. That is hardly useful in the context of events. So I would strongly advice the asker not to declare events whose delegate type returns anything.