Tuesday, September 7, 2010

Covariance and Contravariance feature of .NET 4.0

Hi,
I'll consider below class hierarchy throughout this explanation:

class Account { }
class Savings : Account { }
class Current : Account { }
Now lets begin with Example 1:
class Program
{
delegate T MyDel<T>();
static void Main(string[] args)
{
MyDel<Savings> objSavings = () => new Savings();
MyDel<Account> objAccount = objSavings;
}
}
The code shown in Example 1 will not work in versions prior to 4.0. But if you change generic parameter T to OUT T in 4.0, then this assignment compatibility work via CoVariance. Now check this 4.0 code in Example 2:
class Program
{
delegate T MyDel<out T>();
static void Main(string[] args)
{
MyDel<Savings> objSavings = () => new Savings();
MyDel<Account> objAccount = objSavings;
}
}
The only change in Example 2 is additional OUT keyword.
Now lets move to ContraVariance:
ContraVariance supports the opposite direction of assignment with IN keyword as shown in Example 3:
class Program
{
delegate T MyDel<in T>(T t);
static void Main(string[] args)
{
MyDel<Account> objAccount = (account) => Console.WriteLine(account); MyDel<Savings> objSavings = objAccount;
}
}



These variance come into picture with Generics, Delegates, Interfaces and Collections.

No comments:

Post a Comment