C # delegates support covariance and contravariance , so this should work.
The problem is overload.
delegate void CallBack(A a);
static CallBack callBack = new CallBack(Test);
Which signature of the overload method ( Test(A a)or Test(B b)) should be allowed at compile time, but both can be applied, so an error occurs.
You can avoid this by splitting the overload:
static void TestA(A a)
{
Console.WriteLine("Test(a)");
}
static void TestB(B a)
{
Console.WriteLine("Test(b)");
}
static CallBack callBackA = new CallBack(TestA);
static CallBack callBackB = new CallBack(TestB);
In any case, you can pass B:
callBackA(new B());
callBackB(new B());
Given that you have this contravariance, why do you need overload?
source
share