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.
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.
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.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With