Trevor Hickey Trevor Hickey - 2 months ago 15
C# Question

Can an Action be assigned to a void delegate implicitly?

I have a class that needs constructed with a void delegate:

//an object that's constructed with a "void delegate of no params"
public class BindableCommand
{
public delegate void ExecuteMethod();
private readonly ExecuteMethod _executeMethod;

public BindableCommand(ExecuteMethod executeMethod)
{
_executeMethod = executeMethod;
}
}


It works when its constructed in the following way:

public class Test
{
public static void Main()
{
//creates a bindable command
BindableCommand b = Create();
}

private static BindableCommand Create(){
BindableCommand b = new BindableCommand(Function);
return b;
}

private static void Function(){}
}


I would now like to pass
Function
as an argument before constructing
BindableCommand
.

My attempt fails to compile:

public class Test
{
public static void Main()
{
//creates a bindable command
BindableCommand b = Create(Function);
}

private static BindableCommand Create(Action action){
BindableCommand b = new BindableCommand(action);
return b;
}

private static void Function(){}
}





prog.cs(20,19): warning CS0219: The variable `b' is assigned but its value is never used
prog.cs(24,23): error CS1502: The best overloaded method match for `BindableCommand.BindableCommand(BindableCommand.ExecuteMethod)' has some invalid arguments
prog.cs(9,12): (Location of the symbol related to previous error)
prog.cs(24,43): error CS1503: Argument `#1' cannot convert `System.Action' expression to type `BindableCommand.ExecuteMethod'


But I thought an
Action
was a
void delegate()
?

I can't pass a void delegate:

private static BindableCommand Create(delegate void action){/* ... */}


Do I have to do?

private static BindableCommand Create(BindableCommand.ExecuteMethod action){/* ... */}


Is there a way to have the cast occur automatically?

Answer

But I thought an Action was a void delegate()?

It is. That doesn't mean that there's an implicit conversion between delegate instances with the same signature.

Is there a way to have the cast occur automatically?

No. You could just use Action instead of defining your own delegate in the first place, in which case no conversion will be needed, but if you want to create your own delegate type then you'll need to explicitly convert it to another delegate, regardless of the delegates' signatures.