Covariance allows us to have a more derived type as return type
Contra-variance allows us to have less derived type as parameter type than what is specified in the delegate.
Example:
using System;
using System.Collections.Generic;
public class MyBase
{
public virtual void MyName()
{
Console.WriteLine(“from base”);
}
}
public class Derived : MyBase
{
public override void MyName()
{
Console.WriteLine(“from derived”);
}
}
public class MyClass
{
public delegate MyBase Test(Derived d);
public static void RunSnippet()
{
//C# Delegate Covariance and Contra-variance
//Covariance allows us to have a more derived type as return type
//Contra-variance allows us to have less derived type as parameter type than what is specified in the delegate.
Test t = new Test(TestFunction);
MyFunction(t);
RL();
}
public static void MyFunction(Test t)
{
//WL(t.GetType().ToString());
WL(t.GetInvocationList()[0].Method.Name);
}
public static Derived TestFunction(MyBase d)
{
d.MyName();
Derived d2 = new Derived();
return d2;
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format(“—\nThe following error occurred while executing the snippet:\n{0}\n—“, e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write(“Press any key to continue…”);
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}