Posts

Showing posts from September 12, 2010

C# 4.0 Feature - CoVariance and ContraVariance

Lets see the new feature in C# 4.0 “CoVariance and ContraVariance". This is a very tricky concept and there are many illustrations in the web. If we had to do the following prior to C# 4.0 class Drivers { } class LaptopDriver : Drivers { } class DesktopDriver : Drivers { } class LanDriver : LaptopDriver { } delegate T GetDriver (); static void Main(string[] args) { GetDriver getLaptopDriver = () => new LaptopDriver(); GetDriver getDrivers = getLaptopDriver; Console.ReadLine(); } We would have got a error as follows Cannot implicitly convert type 'ConsoleApplication2.Program.GetDriver ' to 'ConsoleApplication2.Program.GetDriver ' To overcome this in C# 4.0 we have CoVariance which is mainly used for assignment compatability. We need to modify the code by adding a “out” keyoword in the delagate declaration as seen below class Drivers {