What is the difference between eventOne (with keyword 'event') and eventTwo (w/o keyword)?
class Program
{
public event EventHandler eventOne;
public EventHandler eventTwo;
public void RaiseOne()
{
if (eventOne != null)
eventOne(this, EventArgs.Empty);
}
public void RaiseTwo()
{
if (eventTwo != null)
eventTwo(this, EventArgs.Empty);
}
static void Main(string[] args)
{
var p = new Program();
p.eventOne += (s, e) => Console.WriteLine("One");
p.eventTwo += (s, e) => Console.WriteLine("Two");
p.RaiseOne();
p.RaiseTwo();
}
}
eventOne
is a public event backed by a private field of type EventHandler
.eventTwo
is a public field of type EventHandler
.Basically an event only encapsulates the ideas of "subscribe" and "unsubscribe" in the same way that a property only encapsulates the ideas of "get" and "set" rather than the actual storage. (As far as the CLR is concerned an event can also expose a "raise" method, but C# never uses this. Ignore it.)
See my article on events (alternate link) for more about the difference between delegates and events.
By using the event keyword you tell C# go generate to hidden methods, add_XXX and remove_XXX for your underlying delegate. This makes sure that anyone using your class can only attach and remove delegates to the event. The key point is that nobody outside your class and raise the event, so you've got complete control over when this will happen.
If you don't use event then you're just exposing a public delegate that anyone can add to, remove from and invoke. It's highly unlikely that you want anyone other than your class to do the invoking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With