I understand the purpose of events, especially within the context of creating user interfaces. I think this is the prototype for creating an event:
public vo
Just to add to the existing great answers here - building on the code in the accepted one, which uses a delegate void MyEventHandler(string foo)
...
Because the compiler knows the delegate type of the SomethingHappened event, this:
myObj.SomethingHappened += HandleSomethingHappened;
Is totally equivalent to:
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);
And handlers can also be unregistered with -=
like this:
// -= removes the handler from the event's list of "listeners":
myObj.SomethingHappened -= HandleSomethingHappened;
For completeness' sake, raising the event can be done like this, only in the class that owns the event:
//Firing the event is done by simply providing the arguments to the event:
var handler = SomethingHappened; // thread-local copy of the event
if (handler != null) // the event is null if there are no listeners!
{
handler("Hi there!");
}
The thread-local copy of the handler is needed to make sure the invocation is thread-safe - otherwise a thread could go and unregister the last handler for the event immediately after we checked if it was null
, and we would have a "fun" NullReferenceException
there.
C# 6 introduced a nice short hand for this pattern. It uses the null propagation operator.
SomethingHappened?.Invoke("Hi there!");