[ACCEPTED]-Difference between assigning an Action<T> method and subscribing to Action<T> event-delegates
(As an aside, it's hard to explain things 12 when you've used the same type names twice.)
When 11 you use a public field, clients can not 10 only subscribe to events - they can also 9 completely remove other event handlers by assigning instead 8 of adding:
myClass.OnAdd = Add;
They can also invoke the handler directly:
myClass.OnAdd("foo");
Both 7 of these violate the normal pub/sub pattern, where 6 the various subscribers are isolated from 5 one another. Subscribers don't get to overwrite 4 each other's subscriptions (only add or 3 remove their own) and they don't get to 2 raise the event themselves.
For more on events 1 and delegates, see my article on the topic.
You can assign more than one delegates to 1 one event (thus the +=
operator).
An Event acts like a wrapper around a Delegate 3 to offer protection from reassigning/removing 2 as John has pointed out. I found this quite 1 a good read.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.