Events also 'does' something like methods, but they don't have return types and just voids?
I am curious to know, Why is it so? and Why don't they return types?
Do events have return type? By default most event handlers return void (No return type), however, it is possible for handlers to return values.
Events are delegates with a signature that takes an object and an eventargs and returns nothing (Void/Null). Event handlers are subroutines with the same method signature. So the return type is Void, or in other words, there is no return type.
Events in C# are a mechanism that classes use to send notifications or messages to other classes. They are a specialized delegate type that we use to notify other classes when something they listen to happens.
Because events can be handled by multiple listeners. There is not guaranteed order to the event handlers (though I think they're called in the order they are subscribed in reality.)
Instead, for events that want to "return" some data, the convention is to have a mutable EventArgs object such as CancelEventArgs which can have its Cancel property set to true. The advantage of this over a return value is that event handlers in the chain can look at the property to see if another handler already set it. But you still wind up with a situation where the last one to set the property wins.
If it were a return value, the whole concept would be a lot more complicated.
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