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



9 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. 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