What is the return type for an Event in .NET?

11,590

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

Share:
11,590

Related videos on Youtube

Tab
Author by

Tab

Updated on September 16, 2022

Comments

  • Tab
    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
      Amit Singh almost 11 years
      its void...you can see where you define event.....
    • Rao Ehsan
      Rao Ehsan almost 11 years
      Event is object and object doesn't return anything, I think you're asking about event handler..!!
  • Matthew Watson
    Matthew Watson almost 11 years
    Note the difference between an event and an EventHandler
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen almost 11 years
    Good 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 from void 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.