9

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.

Luke Hutton
  • 10,612
  • 6
  • 33
  • 58
saam
  • 471
  • 1
  • 6
  • 9
  • Take a look at this SO question: http://stackoverflow.com/questions/447821/how-do-i-unsubscribe-all-handlers-from-an-event-for-a-particular-class-in-c – Ian Gilroy Mar 13 '13 at 17:51
  • Check out http://stackoverflow.com/questions/1431359/event-action-vs-event-eventhandler for an overview of Action vs EventHandler – PHeiberg Mar 13 '13 at 18:04

4 Answers4

23

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.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
6
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
        }
}
PHeiberg
  • 29,411
  • 6
  • 59
  • 81
  • Thanks for the reply. `public event Action _action;` is this bit ok? Meaning shouldnt Action take parameters from 1 to 16. Shouldnt it be like `public event Action<..> _action;` – saam Mar 13 '13 at 18:03
  • If you need some kind of argument to the action, yes. But there are two versions of the Action class in the BCL. The non-generic you see here (Action) and the generic (Action<>). I'd however recommend to go with the standard event convention of using event EventHandler<>. See my comment on your question. – PHeiberg Mar 13 '13 at 18:07
3

It's removing the handlers for the action.

msarchet
  • 15,104
  • 2
  • 43
  • 66
2

An event is actually a MultiCastDelegate. When you "attach" an event handler, it adds a reference to it's InvocationList.

The code above is detaching each event handler in the InvocationList from the event - essentially "clearing" the event, which could also be done by saying _action = null.

D Stanley
  • 149,601
  • 11
  • 178
  • 240