marbel82 marbel82 - 1 month ago 5x
C# Question

Why can't I add a handler to PropertyChanged with EventHandler attribute type (by reference to method)

I'm doing something like this:

void komar_EventHandler(object sender, EventArgs e)
// Do somethig

Komar k = new Komar();

k.PropertyChanged += komar_EventHandler; // OK (why?)

EventHandler methodRef = komar_EventHandler;

k.PropertyChanged += methodRef; // Error !
k.PropertyChanged += (PropertyChangedEventHandler)methodRef; // Error !

// I know solution, but I don't like it :)
k.PropertyChanged += (s, e) => { methodRef(s, e); };


Why can I add a handler with different type immediately, but I can't use reference to a method?

k.PropertyChanged += komar_EventHandler; // OK (why?)

Because the compiler automatically converts the method group komar_EventHandler to a PropertyChangedEventHandler delegate. It's the same as if your code was:

k.PropertyChanged += new PropertyChangedEventHandler(komar_EventHandler);
k.PropertyChanged += methodRef;                              // Error !

The PropertyChanged event expects a PropertyChangedEventHandler, not an EventHandler. There's no implicit conversion between different delegate types.

k.PropertyChanged += (PropertyChangedEventHandler)methodRef; // Error !

An EventHandler can't be cast to a PropertyChangedEventHandler; it's just not a valid conversion. You can, however, create a PropertyChangedEventHandler from a EventHandler:

k.PropertyChanged += new PropertyChangedEventHandler(methodRef);