Why we need - Covariance & Contravariance - C# 4.0

Hi,

Can you please explain me why we need:

Covariance & Contravariance in C# 4.0 ? Why we need Variance ? I have followed this article but cannot able to understand it - http://arun-ts.blogspot.com/2010/10/c-40-features.html. Can you explain me with simple example in simple terms ?

Thanks
milani_lucieAsked:
Who is Participating?
 
käµfm³d 👽Commented:
P.P.S.

In .NET 3.x, the way to overcome this would be to use something like Linq:

List<ChildClass> list1 = new List<ChildClass>();  // let's pretend there is stuff in this list
List<BaseClass> list2 = list1.Cast<BaseClass>();

Open in new window


In .NET 2.0 (and 3.x), you would have to iterate over the collection:

List<ChildClass> list1 = new List<ChildClass>();  // let's pretend there is stuff in this list
List<BaseClass> list2 = new List<BaseClass>(list1.Count);

foreach (ChildClass c in list1)
{
    list2.Add((BaseClass)c);
}

Open in new window

0
 
käµfm³d 👽Commented:
At a very basic level, this about implicit conversions, and specifically conversions of this type:

List<ChildClass> list1 = new List<ChildClass>();  // let's pretend there is stuff in this list
List<BaseClass> list2 = list1;

Open in new window


In pre-.NET 4.0, you cannot do this, and this is a "flaw" of the generic typing system. Even though you and I know that a ChildClass is a BaseClass, the compiler in pre-4.0 could not determine this. This is where co- and contra-variance come in (in 4.0+). Co- and contra-variance allow the compiler to safely convert generics as exemplified above.

"Co" essentially means converting from a child to a base.
"Contra" essentially means converting from a base to a child.

The above example was an attempt at covariance.
0
 
käµfm³d 👽Commented:
P.S.

The above is not the only instance of variance. As outlined in your referenced article, generic delegates can be affected as well. This is going to be related to generics you use or create, and only if are trying to switch between generics of a base to a child, or between generics of a child to a base.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.