Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Can I cast an explicit delegate to an Action delegate?

Given:

delegate void Explicit();

Can I:

public void Test(Explicit d)
{
    Action a;
    a = d; // ????
}

I have a scenario where I need to overload a constructor that has:

public MyClass(Expression<Action> a) {}

but the following overload is ambiguous:

public MyClass(Action a) {}

I figured using an explicit delegate would resolve the ambiguity but I need to cast that explicit delegate to an action in order to leverage the existing code.

like image 745
Dane O'Connor Avatar asked Nov 29 '22 04:11

Dane O'Connor


2 Answers

Action a = new Action(d);
like image 153
Yuriy Faktorovich Avatar answered Dec 10 '22 03:12

Yuriy Faktorovich


No you cannot cast different delegate types with matching signatures between each other. You must create a new delegate / lambda expression of the target type and forward into the original one.

like image 38
JaredPar Avatar answered Dec 10 '22 02:12

JaredPar