Search code examples
c#genericsdelegatescontravariancevariance

Generic delegate contravariance compilation error


I'm using the MSDN examples for variance in delegate. But the following code is giving me a compilation error. Based on my understanding, it should accept the First as an argument. What am I doing wrong? The code sample.

SampleGenericDelegate<Second, First> secdel = AFirstRSecond;
secdel(new First()); //compilation error here.

public class First { }
public class Second : First { }
public delegate R SampleGenericDelegate<A, R>(A a);
public static Second AFirstRSecond(First first)
{ 
    return new Second(); 
}    

Errors

Delegate 'ConsoleApplication1.SampleGenericDelegate<ConsoleApplication1.Second,
ConsoleApplication1.First>' has some invalid arguments

Argument 1: cannot convert from 'ConsoleApplication1.First' to    
'ConsoleApplication1.Second'    

Solution

  • secdel has an argument type of Second, so you need to pass an instance of that:

    SampleGenericDelegate<Second, First> secdel = AFirstRSecond;
    secdel(new Second());