views:

415

answers:

3

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.

+6  A: 
Action a = new Action(d);
Yuriy Faktorovich
While this works, it should be noted that it actually creates a new delegate instance which references `d.Invoke`. If you keep doing this, the delegate chain will grow, and every invocation of such delegate will result in a chain of virtual `Invoke` calls, so there is a certain perf hit (not that it's likely that you run into this problem in practice).
Pavel Minaev
+7  A: 

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.

JaredPar
This feature was requested way back in 2006 and was rejected.http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=159810
alex
+1  A: 

You can also specify the Invoke method to create the new Action delegate

Action a = new Action(d.Invoke);
thecoop