Let's say I have a "Processor" interface exposing an event - OnProcess. Usually the implementors do the processing. Thus I can safely subscribe on this event and be sure it will be fired. But one processor doesn't do processing - thus I want to prevent subscribers to subscibe on it. Can I do that? In other words in the code below I want the last line to throw an exception:
var emptyProcessor = new EmptyProcessor();
emptyProcessor.OnProcess += event_handler; // This line should throw an exception.
To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.
Events are blocking (meaning that they run synchronously with the thread that calls them).
In C#, event handler will take the two parameters as input and return the void. The first parameter of the Event is also known as the source, which will publish the object. The publisher will decide when we have to raise the Event, and the subscriber will determine what response we have to give.
An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application. Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface.
class EmptyProcessor : IProcessor {
[Obsolete("EmptyProcessor.OnProcess should not be directly accessed", true)]
public event EventHandler OnProcess {
add { throw new NotImplementedException(" :( "); }
remove { }
}
}
In this situation, the true
parameter on Obsolete causes a compile-time exception. so:
EmptyProcessor processor1 = new EmptyProcessor();
IProcessor processor2 = new EmptyProcessor();
processor1.OnProcess += handler; // <-- compile-time error
processor2.OnProcess += handler; // <-- run-time error
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