Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why events have no return types in .NET?

Tags:

.net

events

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?

like image 249
Dhanapal Avatar asked May 29 '09 06:05

Dhanapal


People also ask

Can event have return type?

Do events have return type? By default most event handlers return void (No return type), however, it is possible for handlers to return values.

What is the return type of an event in net?

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.

What type is event C#?

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.


1 Answers

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.

like image 154
Josh Avatar answered Sep 29 '22 10:09

Josh