Saturday, January 24, 2015

Covariance Contravariance C# simple example

In .NET 4.0 Microsoft presented covariance (out) and contravarince (in). Next image shows simple class hierarchy:


Imagine there is a need of animal container class that can only return data
interface IAnimalHub<T>
        where T: Animal
    {
        T GetAnimal();
    }
We can declare and work with animal hub type as
  IAnimalHub<Animal> hub1 = new AnimalHub<Animal>();

Can we generalise left part or, in other word, downgrade type
 IAnimalHub<Animal> hub2 = new AnimalHub<Lion>();
 IAnimalHub<Animal> hub3 = new AnimalHub<Cat>();

Definitely it is possible, because we are going only to take out data and work with it, whether it is Lion or Cat. This idea is called covariance and can be done with out keyword in C#:
interface IAnimalHub<out T>
        where T: Animal
    {
        T GetAnimal();
    }

Now what if we have Add method with some animal argument in addition to our Get method
interface IAnimalHub<out T>
        where T: Animal
    {
        T GetAnimal();

        void Add(T animal);
    }

Should it work?
No! And the reason is that otherwise it would be possible to do
IAnimalHub<Lion> hub = new AnimalHub<Lion>();
var dog = new Dog();
hub.Add(dog);

So one cannot expect possibility to Add dog while waiting Lion object. It means covariance works only with returning data (out).

What about contrvarience?

As the word says this works in the opposite to covariance. Contrvariance expects only methods where one can put/write/insert data. In C# this is presented with in keyword. Consider only Add method in our interface:
    interface IAnimalHub<in T>
        where T: Animal
    {
        void Add(T animal);
    }

 Now we can do the opposite
 
            IAnimalHub<Animal> hub1 = new AnimalHub<Animal>();
            IAnimalHub<Lion> hub2 = new AnimalHub<Animal>();
            IAnimalHub<Cat> hub3 = new AnimalHub<Animal>();
            IAnimalHub<Dog> hub4 = new AnimalHub<Animal>();

In other words we can put Lion, Cat or Dog object where we expect Animal.

Limitations

Covariance and contrvariance can be declared only in the interface or delegate, not class. Generic parameter can be only reference type, not value type.

Examples  

In .NET IEnumerable<T> only returns data, so it is created as covariant IEnumerable<out T> in version 4 of the framework. And we simply can do
Animal[] animals = new Lion[0];
Animal[] animals = new Cat[0];
IEnumerable<Animal> animals = new Lion[0];
IEnumerable<Animal> animals = new Cat[0];



17 comments:

  1. Covariance basically means that the return value of a method that is referenced by your delegate can have a different return type than that specified by the delegate itself, as long as the return type of the method is a subclass of the return type of the delegate.
    Contravariance deals with the parameters data types rather than return data types.
    Online Dot Net Training
    Dot Net Training in Chennai

    ReplyDelete
  2. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.

    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    rpa course in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  3. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  4. I’ve desired to post about something similar to this on one of my blogs and this has given me an idea. Cool Mat.
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete
  5. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.
    python Course in Pune
    python Course institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  6. Awesome..You have clearly explained …Its very useful for me to know about new things..Keep on blogging..
    AWS Training in pune
    AWS Online Training
    AWS Training in Bangalore

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Really useful information. Thank you so much for sharing. It will help everyone. Keep Post.

    Best SAP Training in Bangalore for SAP, we provide the sap training project with trainers having more than 5 Years of sap training experience, we also provide 100% placement support.

    ReplyDelete
  9. Its very useful for me to know about new things..i do agree your blog for quiz programming concepts, which is very helpful to grow up your knowledge. keep sharing more...


    aws training in chennai | aws training in annanagar | aws training in omr | aws training in porur | aws training in tambaram | aws training in velachery

    ReplyDelete
  10. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described.
    python training in chennai

    python online training in chennai

    python training in bangalore

    python training in hyderabad

    python online training

    python flask training

    python flask online training

    python training in coimbatore

    ReplyDelete

  11. 360DigiTMG, Indore is a leading solutions provider of Training and Consulting to assist students, professionals by delivering top-notch, world-class classroom and online training. It offers artificial intelligence training in indore.

    ReplyDelete
  12. I was searching this concept. Finally, I got it which contains effective examples. This article inspired me to read more. This article resolved my all queries. Thank you for sharing your knowledge on this type of websites. keep sharing!

    Aws Training in Chennai

    Aws Training in Velachery

    Aws Training in Tambaram

    Aws Training in Porur

    Aws Training in Omr

    Aws Training in Annanagar

    ReplyDelete
  13. This bulletin transformed into composed through an exact reasoning essayist. I set up the different pondering the steady focuses made through the creator. unwell be announcement. Dll Files Fixer Crack

    ReplyDelete
  14. Thankful to you for substitute insusceptible article. what other spot could have to every one of us suspect that devout of divulge in any such get normal for creating? i've a show adjoining week, and I'm concerning the see for such real factors.
    Office 2010 Activation Crack

    ReplyDelete
  15. I was hundreds of miles away on your special day. I hope you enjoyed your day with a big cake. Happy Belated Birthday Images

    ReplyDelete