C# events vs. delegates

Event invocation
Furthermore, an event can only be invoked from within the class that declared it, whereas a delegate field can be invoked by whoever has access to it. For example:

[sourcecode language="csharp"]
using System;
namespace EventAndDelegate
{
 delegate void MsgHandler(string s);

 class Class1
 {
 public static event MsgHandler msgNotifier;
 public static MsgHandler msgNotifier2;

 static void Main(string[] args)
 {
 new Class2().test();
 }
 }

 class Class2
 {
 public void test()
 {
 Class1.msgNotifier("test"); // error CS0070: The event 'EventAndDelegate.Class1.msgNotifier' can only appear on the left hand side of += or -= (except when used from within the type 'EventAndDelegate.Class1')
 Class1.msgNotifier2("test2"); // compiles fine
 }
 }
}
[/sourcecode]

This restriction on invocations is quite strong. Even derived classes from the class declaring the event aren’t allowed to fire the event. A way to deal with this is to have a protected virtual method to trigger the event.

 

Conclusion
We have seen that the event keyword is a modifier for a delegate declaration that allows it to be included in an interface, constraints it invocation from within the class that declares it, provides it with a pair of customizable accessors (addand remove) and forces the signature of the delegate (when used within the .NET framework).

廣告