Can we have the same delegate for two events

Do we have the same delegate for two events? which have the same number of inputs? or delegate and events have a one to one relationship?

+2


a source to share


3 answers


Of course, many events use EventHandler as a simple delegate.

Or do you mean that you can subscribe to many events to the same method? This is also possible, you can subscribe, for example. Subscribe TextChanged-Events from all text boxes to the same delegate. Especially for Validated and Validated events, it is useful to use only one method for all fields that use the same validation logic.



Events are generally multicast in .NET, so you can subscribe to many delegates to a single event. For example, you can specify two or three methods for validating text boxes and subscribe the TextBox.Validating event to all methods that validate one aspect of the input.

+4


a source


Do you mean using the same delegate type for two different event declarations, or using the same delegate instance to subscribe to two different events? Both are allowed:



public event EventHandler Foo;
public event EventHandler Bar;
...
EventHandler handler = SomeMethod;
Foo += handler;
Bar += handler;

      

+4


a source


As long as the event handlers are the same, you can have the same handler for as many events as you like.

From MSDN :

The delegate type defines the set of arguments passed to the method that handles the event. Multiple events can use the same delegate type , so this step is only necessary if a suitable delegate type has not already been declared.

0


a source







All Articles