C# 4 delegates contravariance

A little quiz.

Given the following two delegates:

delegate void EventHandler(object sender, EventArgs e);


delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);

Does the following code compile?

void propertyHandler(object sender, PropertyChangedEventArgs e)

{ }


EventHandler handler = propertyHandler;

Did you answer "YES, because PropertyChangedEventHandler IS an EventHandler"?

Unfortunately, the answer is no. Imagine how would the following code work:

handler(this, new EventArgs());

How could just EventArgs be passed to propertyHandler, which expects PropertyChangedEventArgs?

Actually, the exact opposite is correct in C# 4:

void handler(object sender, EventArgs e)

{ }


PropertyChangedEventHandler propertyHandler = handler;

Then, calling

propertyHandler(this, new PropertyChangedEventArgs("Name"))

is perfectly ok, because the handler just sees passed PropertyChangedEventArgs as EventArgs.

So the conclusion is: you can handle specialized events using less specialized handlers (you can handle eg. PropertyChanged event using just an EventHandler).

For more info, see C# delegates on msdn.

Posted by Martin Konicek on 4:58 AM 0 comments