Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between assigning an Action<T> method and subscribing to Action<T> event

Lets say I have the below code. What is the difference between assigning the actions directly and subscribing to an event?

//Action directly assigned
public class ClassA
{
  public Action<string> OnAdd;

  private void SomethingHappened()
  {
     OnAdd("It Happened");
  }
}

public class ClassB
{

  public ClassB()
  {
    var myClass = new ClassA();
    myClass.OnAdd =  Add;
  }

  private void Add(string Input)
  {
    //do something
  }  
}

//Event handlers
public class ClassA
{
  public event Action<string> OnAdd;

  private void SomethingHappened()
  {
    if (OnAdd != null)
     OnAdd("It Happened"); //Should it be OnAdd.Invoke("It Happened") ???????
  }
}

public class ClassB
{

  public ClassB()
  {
    var myClass = new ClassA();
    myClass.OnAdd += Add;
  }

  private void Add(string Input)
  {
    //do something
  }  
}
like image 457
Jon Avatar asked Feb 13 '12 10:02

Jon


2 Answers

(As an aside, it's hard to explain things when you've used the same type names twice.)

When you use a public field, clients can not only subscribe to events - they can also completely remove other event handlers by assigning instead of adding:

myClass.OnAdd = Add;

They can also invoke the handler directly:

myClass.OnAdd("foo");

Both of these violate the normal pub/sub pattern, where the various subscribers are isolated from one another. Subscribers don't get to overwrite each other's subscriptions (only add or remove their own) and they don't get to raise the event themselves.

For more on events and delegates, see my article on the topic.

like image 193
Jon Skeet Avatar answered Oct 16 '22 07:10

Jon Skeet


You can assign more than one delegates to one event (thus the += operator).

like image 31
linepogl Avatar answered Oct 16 '22 07:10

linepogl