Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert delegate to identical delegate?

Tags:

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?

like image 686
SkyN Avatar asked Oct 28 '10 06:10

SkyN


2 Answers

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
like image 76
Jon Skeet Avatar answered Oct 11 '22 10:10

Jon Skeet


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.

like image 26
Thomas Levesque Avatar answered Oct 11 '22 09:10

Thomas Levesque