I have recently discovered the use of Actions and anonymous functions and how they can be handy when working with tasks. I have done a couple of tests, passing anonymous functions into a class to work similarly to an event.
An example of what Im doing would be...
var myForm = new MyForm();
myForm.OnCertainEvent(output => {
//interact with UI based on feedback.
}));
Then in the form itself, I would set an Action property with the Action passed into the OnCertainEvent method.
I think this syntax is very clean instead of declaring events, delegates, and hooking them up with the += syntax.
Would this be bad practice to do? Obviously it isn't traditional, but does it have any negative effects? Essentially I'm just providing a callback.
Would this be bad practice to do?
This is a very circumstantial question. It really depends on several key factors, like:
Action, Action<T> delegate?Action or Action<T> delegate callback as the event handler?It seems as though you are trying to assign a callback as an event handler, but the way you implemented it seems incorrect. It seems like you are trying to register your callback via a method namely OnCertainEvent, the flaw is that this could be called multiple times by the consumer and essentially you'd end up with the same number of executions as the number of callbacks invoked -- does that make sense?
Events are multicast, which means you can wire up an infinite number of handlers to listen as a callback on a single event that is fired. Here is an example of what I'm talking about, I wrote up a quick .NET Fiddle. The way this is written it is never able to unsubscribe the listeners since they are anonymous, which can lead to problems.
Obviously it isn't traditional, but does it have any negative effects?
As long as you're aware of the consequences and you correctly clean up your code it should be fine. In a situation where you want to handle an event like this, you can do so more safely by having the constructor of your class (in your specific case a MyForm). Here is another .NET Fiddle to demonstrate this.
It is totally possible and super powerful, and in my opinion now considered "traditional". The notion of creating your own delegate implementations is gone and has been since the introduction of generics and lambda expressions. The last link was a shameless plug, I hope all of this makes sense and answers your question!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With