Event in C#

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:
if (SomethingHappened != null) // the event is null if there are no listeners!
{
SomethingHappened(“Hi there!”);
}

Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]

click to change验证码

无觅相关文章插件