Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delegate covariance and Contavariance

Consider the following code snippet

namespace ConsoleApplication1
{

public delegate TResult Function<in T, out TResult>(T args);

 class Program
 {
      static void Main(string[] args)
    {
        Program pg =new Program();
        Function<Object, DerivedClass> fn1 = null;
        Function<String, BaseClass> fn2 = null;
        fn1 = new Function<object, DerivedClass>(pg.myCheckFuntion)
        fn2=fn1;
        fn2("");// calls myCheckFuntion(Object a)
        pg.myCheckFuntion("Hello"); //calls myCheckFuntion(String a)
     }

     public DerivedClass myCheckFuntion(Object a)
    {
        return  new DerivedClass();
    }
    public DerivedClass myCheckFuntion(String a)
    { 
        return new DerivedClass();
    }
 }

why the delegate call and normal method invocation call different methods.

like image 265
Ashley John Avatar asked Jul 22 '11 14:07

Ashley John


People also ask

What is difference between covariance and contravariance?

In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.

What is delegate covariance?

C# Delegate Covariance allows us to call a method that has derived return type of the delegate signature return type. It means we can call a method that returns parent or child class object.

What is covariance and contravariance in Java?

Covariance can be translated as "different in the same direction," or with-different, whereas contravariance means "different in the opposite direction," or against-different. Covariant and contravariant types are not the same, but there is a correlation between them. The names imply the direction of the correlation.


1 Answers

The delegate is bound to myCheckFuntion(Object) at compile time - you're telling it to find a method which accepts an Object. That binding is just to a single method - it doesn't perform overload resolution at execution time based on the actual argument type.

When you call pg.myCheckFuntion("Hello") that will bind to myCheckFuntion(String) at compile-time because "Hello" is a string, and the conversion from string to string is preferred over the conversion from string to object in overload resolution.

Note that if you write:

object text = "Hello";
pg.myCheckFuntion(text);

then that will call myCheckFuntion(Object).

like image 138
Jon Skeet Avatar answered Sep 19 '22 10:09

Jon Skeet