I have the follow program:
static void Main(string[] args)
{
CaptureFunction(MyFunction); // This line gets an error: "The call is ambiguous between the following methods or properties: CaptureFunction(System.Func<object,object>) and CaptureFunction(System.Func<int,int>)"
CaptureFunction(MyFunction2);
}
static void CaptureFunction(Func<object,object> myFunction)
{
myFunction.DynamicInvoke(3);
}
static void CaptureFunction(Func<int, int> myFunction)
{
myFunction.DynamicInvoke(3);
}
static object MyFunction(object a)
{
if (a is int)
return ((int) a)*3;
return 0;
}
static int MyFunction2(int a)
{
return a * 3;
}
I am trying to figure out why I am getting an ambiguity error at that line. They clearly have two different parameter signatures. I understand that an int can also be boxed into an object, however, I would except C# to call the CaptureFunction(Func<int, int>) method if I pass actual int values, otherwise it should call the other CaptureFunction() method. Can someone please explain this and please offer a possible work around?
This is due to covariance/contavariance introduced in .Net 4. See here for info. BecauseSorry, not .Net 4intis castable toobjectthe compiler can’t decide which function you are pointing to (as Func is castable to Func)The following compiles:
Note the casting to
Func<object,object>