I'm not sure what you mean when you say consumers will need to "create Delegates
". Here's an example I came up with which works just fine and it doesn't seem that hard to do for consumers of your method.
private static void HigherOrderFoo(Delegate foo)
{
var returnVal = foo.DynamicInvoke(null);
}
private static void Bar()
{
HigherOrderFoo((Func<int>)(() => 10));
}
Likewise, the lambda function could just as well have been a method group and casting that to a delegate type would also have worked.
private static void HigherOrderFoo(Delegate foo)
{
var returnVal = foo.DynamicInvoke(null);
}
private static void Bar()
{
HigherOrderFoo((Func<int>)Baz);
}
private static int Baz()
{
return 10;
}
Also, here's a great answer by Jon Skeet which explains why you need to cast the parameter to the actual delegate type in order to convert it to a Delegate
.
Edit: If the method you're passing in as a parameter had it's own parameters, you could probably use the params
keyword to pass in the parameters to HigherOrderFoo
.
private static void HigherOrderFoo(Delegate foo, params object[] list)
{
var bar = foo.DynamicInvoke(list);
}
private static void Bar()
{
HigherOrderFoo((Func<int, int>)Baz, 10);
}
private static int Baz(int val)
{
return val * val;
}