class MyClass
{
public event Action<string> OnAction;
public event Func<string, int> OnFunc;
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
/// I need to handle arbitrary events.
/// But I see no way to create anonymous delegates in runtime
/// with arbitrary returns and parameters. So I choosed to
/// create multiple “signatures” with different parameter
/// number (up to 10) and different returns (either the Action or
/// Func). While Actions<> work pretty well, the Funcs<> do not.
Action<dynamic> someAction = delegate(dynamic p1) { };
Func<dynamic, dynamic> someFunc = delegate(dynamic p1) { return 42;};
// OK
mc.OnAction += someAction;
// Error: “Cannot implicitly convert type 'System.Func<dynamic,dynamic>'
// to 'System.Func<string,int>'”
mc.OnFunc += someFunc;
// It doesn't work this way as well (the same error message):
// dynamic someFunc = new Func<dynamic, dynamic>((dynamic n1) => { return 42; });
// Let's try another way
// 1:
// Cannot convert anonymous method to delegate type 'System.Func<string,int>'
// because the parameter types do not match the delegate parameter types.
// 2 (even more funny):
// Parameter 1 is declared as type 'dynamic' but should be 'string'.
mc.OnFunc += delegate(dynamic p1) { return 42; };
}
}
Why does it work for actions and doesn't for functions?
In other words, I just would like to know why Action<dynamic> → Action<string>
is ok while Func<dynamic,dynamic> → Func<string, int>
is not. Thanks.