Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of Action and Events

Tags:

c#

events

I am a bit new to c# so please overlook if you find it trivial. I saw the following "weird" code.

Can anybody shed a bit of light on it.

public event Action _action;

if (_action != null)            
{
    foreach (Action c in _action.GetInvocationList())
    {
         _action -= c;
    }
}

Specially the _action -= c; part.

like image 397
saam Avatar asked Mar 13 '13 17:03

saam


People also ask

Where do we use events?

You generally use events to notify subscribers about some action or state change that occurred on the object. By using an event, you let different subscribers react differently, and by decoupling the subscriber (and its logic) from the event generator, the object becomes reusable.

What are events in C# with example?

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.


3 Answers

A delegate can be a delegate to more than one function. If you have a delegate alpha that delegates to Alpha() and a delegate beta that delegates to Beta() then gamma = alpha + beta; is a delegate that calls Alpha() then Beta(). gamma - beta produces a delegate that calls Alpha(). It's a bit of a weird feature, to be perfectly frank.

The code you've posted is bizarre. It says "go through the list of functions in action, produce a whole pile of delegates that invoke fewer and fewer functions, and then finally assign a delegate that does nothing to action. Why on earth would anyone do this? Just assign null to action and be done with it.

like image 84
Eric Lippert Avatar answered Oct 11 '22 20:10

Eric Lippert


public event Action _action; //an event


if (_action != null) // are there any subscribers?

{
        foreach (Action c in _action.GetInvocationList()) //get each subscriber
        {
            _action -= c; //remove its subscription to the event
        }
}
like image 22
PHeiberg Avatar answered Oct 11 '22 20:10

PHeiberg


It's removing the handlers for the action.

like image 45
msarchet Avatar answered Oct 11 '22 21:10

msarchet