The difference between assigning an Action <T> method and subscribing to an Action <T> event
Let's say I have the code below. What is the difference between assigning 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 } } (Aside, it's hard to explain when you used the same type names twice.)
When using an open field, clients can not only subscribe to events - they can also completely delete other event handlers, assigning instead of adding:
myClass.OnAdd = Add; They can also reference the handler directly:
myClass.OnAdd("foo"); Both of them violate the normal pub / additional template, where different subscribers are isolated from each other. Subscribers cannot rewrite each other's subscriptions (just add or remove their own), and they cannot raise the event themselves.
For more information on events and delegates, see my related article .