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];



33 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
    Replies
    1. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Final Year Projects for CSE.

      Software management seeks for decision support to identify technologies like JavaScript that meet best the goals and characteristics of a software project or improvement programme. JavaScript Training in Chennai Accessible experiences and repositories that effectively guide that technology selection are still lacking.

      Aim of technology domain analysis is to describe the class of context situations (e.g., kinds of JavaScript software projects) in which a software engineering technology JavaScript Training in Chennai can be applied successfully

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ReplyDelete
  3. 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
  4. 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
  5. 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
  6. 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
  7. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    AWS Training in Bangalore | Best AWS Amazon Web Services…
    Amazon Web Services (AWS) Training in Pune India
    AWS Training | AWS Training and Certification | AWS online training
    AWS Training in Bangalore cost| Aws training in Bangalore with placements

    ReplyDelete
  8. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    microsoft azure training in bangalore
    rpa training in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  9. 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
  10. This comment has been removed by the author.

    ReplyDelete
  11. 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
  12. 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
  13. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. data science course in coimbatore

    ReplyDelete
  14. 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
  15. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    data science course in coimbatore

    ReplyDelete

  16. 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
  17. 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
  18. Thanks for posting the best information and the blog is very helpful.python course in Bangalore

    ReplyDelete
  19. Acquire the trending Selenium training in Chennai from the best software training institute in Chennai, Infycle Technologies. Additionally, we come up with the latest demanded technological courses like Python, Data Science, Digital Marketing, Big Data, Oracle, AWS, Azure, Google Cloud, Java, and Oracle with the best faculties in the industry. To clear your doubts, call +91-7504633633 or +91-7502633633.

    ReplyDelete
  20. Great post. keep sharing such a worthy information.
    Hadoop Training in Chennai

    ReplyDelete
  21. 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
  22. 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
  23. 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