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.
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

}

Advertisements

About Shashi Kuppa

I have 14 years of Information System experience. My background ranges from software architecture, analysis, design and development to team leadership and project management. My primary strengths include .Net system architecture, object oriented development using C#, web development using Asp.net and SQL server development, reporting and integration. I am an excellent team player, good communicator and have a proven track record for goal-oriented project leadership and management
This entry was posted in Development. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s