Return a value from an Event -- is there a Good Practice for this? Return a value from an Event -- is there a Good Practice for this? multithreading multithreading

Return a value from an Event -- is there a Good Practice for this?


It's often awkward to return values from events. In practice, I've found it much easier to include a writable property on a set of custom EventArgs that is passed to the event, and then checked after the event fires -- similar to Cancel property of the WinForms FormClosing event.


I don't think it's a good idea... events are basically multicast delegates, so there can be multiple handlers. Which return value will you take in that case ?


I know this is ages after the post but thought of adding comment with code to explain Dustin Campbell answer for if someone else comes across this thread. I came across this post while trying to decide what would be best practice and this is what is meant by the answer.

Create your own custom event handler class

public class myCustomeEventArgs:EventArgs{    public bool DoOverride { get; set; }    public string Variable1 { get; private set; }    public string Variable2{ get; private set; }    public myCustomeEventArgs(string variable1 , string variable2 )    {        DoOverride = false;        Variable1 = variable1 ;        Variables = variable2 ;    }}

So when you create your event delegate you use your created event args like this.

public delegate void myCustomeEventHandler(object sender, myCustomeEventArgs e);

And in the class raising the event you declare the event.

public event myCustomeEventHandler myCustomeEvent;

So when you trigger the event in your class the class that listens for the event you can just in the body of the event set e.DoOverride = true; as it will be declared in the class firing the event.

Fire event for example:

if(myCustomeEvent != null){    var eventArgs = new myCustomeEventArgs("Some Variable", "Another Varaible");    myCustomeEvent(this, eventArgs);    //Here you can now with the return of the event work with the event args    if(eventArgs.DoOverride)    {       //Do Something    }}