Covariance and Contravariance in C#

Ahteshamax
Posted by in C# category on for Beginner level | Points: 250 | Views : 415 red flag

In this article will discuss about the concept of Covariance and Contravariance.

This was introduced in version 4.0 as a new C# feature.

Definition: Covariance means variance of the same type. Under parent-child relationship and in dynamic polymorphism, parent can call child object dynamically. Also child class will have parent class functionality and also it will have its own functionally included. It helps in maintaining assignment and works perfectly fine especially if huge collection like IEnumerable, List or Array are used.

Whereas Contravariance is built from contra-variance and in that “contra” means opposite which we can say opposite of Covariance with this child object can call parent object and it works absolutely fine.

Use: Firstly it is used in Object Oriented Programming(OOP) scenario where we have parent and child relationship and specially under dynamic polymorphism whereas the name say dynamic means under runtime and polymorphism mean changing behavior of the object. Together “dynamic polymorphism” meaning we can put it at changing behavior at runtime.

On Visual Studio: In dynamic polymorphism parent object points towards child object and on runtime parent object called “Human” can point to child object “Man” or ‘Woman” and change child object behavior.

After code writing finished just build the solution and check by running it. Below is the image given which is successfully validating that above given line of code. This states that above line of code are perfectly valid.

In general before to C# 4.0 this was very much possible with single parent object pointing to single child object and also dynamically pointing to any of the single child object was also achievable.

But what about when we point collections like “IEnumerable”, list or arrays object pointing list. Will that be acceptable?

If you do the same under .NET Framework 3.5 and below it will not allow you to execute such code.

Covariance

But yes if you use C# 4.0 it is possible with the introduction to covariance this can be achievable. With the use of covariance assigning is maintained even with collection of objects especially under this scenario where we have parent-child relationship.

On Visual Studio if you write a code line where “IEnumerable” human object is pointing to list of Man is acceptable internally using “out” keyword and its type parameter is covariant.

If you view from Object oriented programming(OOP) lens, code of line which were working after assigning single object “objHuman” to Man or Woman as shown in the above image. So when used with customized interface like “IEnumerable” which is covariant enabled in C# 4.0 will also work after assigning group of human i.e. “IEnumerable<Human>” to List<Man> or <Woman>.

Please Note: Enabling covariant is done by using “out” keyword.

Contravariance

Contravariance is exactly opposite of covariance under it child object will point towards parent object and this exactly vice-versa which we earlier did in covariant.

In order to create an example for it we have create a delegate and make use of “in” keyword. Let us below construct the lines of code which will be an example of contravariance.

Below image depicts code example of contravariance where we have done the following: -

  1. Create a function called “ProFunc” which will pass “Human” object and with that variable “Name” will be displayed using the console line on the console.
  2. Under class “Human” declare variable name “Name” and initiate it.
  3. Declare delegate which would be very general it can be “Human”, “Man” or “Woman” with name “MyPtr” any object through it with “in” keyword.
  4. Now create “Human” pointer with name “HmPtr” and point delegate pointer to “ProFunc” function.
  5. Now create one more child pointer using “Man” with name “MnPtr” and this will point to parent “Human”.

Now all the error while writing the code have gone finally just build and run the solution to check whether the code written is perfectly well.

Once found build is successfully done then it means that code is perfect and our contravariance is working with use of “in” keyword where child class “Man” is pointing to parent class “Human”.

Hope that the term covariance and contravariance is clear with above demonstration to all reader.

Below is one fine fresher video uploaded on YouTube from project based series to learn C#: -

Page copy protected against web site content infringement by Copyscape

About the Author

Ahteshamax
Full Name: Ahtesham Shaikh
Member Level: Bronze
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
http://www.learnmsbitutorials.net/
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)