There are two descriptions of the delegate: first, in a third-party assembly:
public delegate void ClickMenuItem (object sender, EventArgs e)
second, the standard:
public delegate void EventHandler (object sender, EventArgs e);
I'm trying to write a method that will receive a parameter of type EventHandler and will call third-party library, with the parameter ClickMenuItem.
How to convert the ClickMenuItem to EventHandler?
Fortunately, it's simple. You can just write:
ClickMenuItem clickMenuItem = ...; // Wherever you get this from
EventHandler handler = new EventHandler(clickMenuItem);
And in reverse:
EventHandler handler = ...;
ClickMenuItem clickMenuItem = new ClickMenuItem(handler);
This will even work in C# 1.0. Note that if you then change the value of the original variable, that change won't be reflected in the "converted" one. For example:
ClickMenuItem click = new ClickMenuItem(SomeMethod);
EventHandler handler = new EventHandler(click);
click = null;
handler(this, EventArgs.Empty); // This will still call SomeMethod
In addition to other answers, if you want to do convert between compatible delegate types without knowing the type at compile time, you can do something like that:
static Delegate ConvertDelegate(Delegate sourceDelegate, Type targetType)
{
return Delegate.CreateDelegate(
targetType,
sourceDelegate.Target,
sourceDelegate.Method);
}
It can be useful if you need to subscribe to an event dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With