Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: understanding event syntax

Tags:

c#

i need some help understanding how i can create a new custom event. i read from here ...

public delegate void ChangingHandler (object sender, CarArgs ca); 
public event ChangingHandler Change; 
...
private void car_Change(object sender, CarArgs ca) {
    MessageBox.Show(ca.Message());
} 
...
car.Change+=new Car.ChangingHandler(car_Change); // add event handler
...
Change(this,ca); // call event

1st, i dont really get the delegate part. in a normal variable declartion,

protected string str1;

but here i have the extra (ChangingHandler). how do i make sense of this? i know its something like a ChangingHandler will be used for handling the event but it throws me off abit.

public event ChangingHandler Change

then

car.Change+=new Car.ChangingHandler(car_Change)

i dont really get the syntax new Car.ChangingHandler(car_Change).

like image 878
Jiew Meng Avatar asked Aug 23 '10 13:08

Jiew Meng


1 Answers

An event in C# is sort of like a collection of method pointers. It says "hey everyone, if you care about me, give me a pointer to a method I can invoke, I'll hold onto it, and when I feel like announcing to the world what is up, I'll invoke all the methods you gave me."

That way someone can give the event a pointer to their method, which is referred to as a "event handler". The event will call this method whenever the event's owner feels it is appropriate.

The delegate, in this sense, is nothing more than saying what kind of method the event will accept. You can't have one person giving the event a method that takes no arguments and one that takes 5, it'd have no idea how to call them. So the delegate is the contract between the event and the event handler, telling them both what to expect for the method signature.

In your case, it is probably better to just use EventHandler<T>, which is a built in delegate of the form void EventHandler<T>(object sender, T eventArgs) for your event delegate, like this:

public event EventHandler<CarArgs> Change;

C# doesn't actually have function pointers in the raw sense. Delegates handle this instead. They are like strongly typed, object oriented function pointers. When you call

car.Change+=new Car.ChangingHandler(car_Change);

You are giving the event a new delegate (function pointer) that points to your car_Change event handler, telling the event to call your car_Change method when it is ready. The delegate (new ChangeHandler(...) simply wraps the pointer to the car_Change method.

like image 55
Matt Greer Avatar answered Oct 08 '22 14:10

Matt Greer