In this post I’ll try to answer the most common questions I find on forums and in documentation feedback about C# covariance and contravariance. It’s a big topic for a single blog post, so expect to see a lot of “more information” links.
Special thanks to Eric Lippert and Chris Burrows for reviewing and providing helpful comments.
What are covariance and contravariance?
In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments.Covariance preserves assignment compatibility and contravariance reverses it.
The following code demonstrates the difference between assignment compatibility, covariance, and contravariance.
// Assignment compatibility.
string str = "test";
// An object of a more derived type is assigned to an object of a less derived type.
object obj = str;
// Covariance.
IEnumerable<string> strings = new List<string>();
// An object that is instantiated with a more derived type argument
// is assigned to an object instantiated with a less derived type argument.
// Assignment compatibility is preserved.
IEnumerable<object> objects = strings;
// Contravariance.
// Assume that I have this method:
// static void SetObject(object o) { }
Action<object> actObject = SetObject;
// An object that is instantiated with a less derived type argument
// is assigned to an object instantiated with a more derived type argument.
// Assignment compatibility is reversed.
Action<string> actString = actObject;
In C#, variance is supported in the following scenarios:
Covariance in arrays (since C# 1.0)
Covariance and contravariance in delegates, also known as “method group variance” (since C# 2.0)
Variance for generic type parameters in interfaces and delegates (since C# 4.0)
What is array covariance?
Arrays are covariant since C# 1.0. You can always do the following:
object[] obj = new String[10];
In the above code, I assigned an array of strings to an array of objects. So I used a more derived type than that originally specified, which is covariance.
Covariance in arrays is considered “not safe,” because you can also do this:
obj[0] = 5;
This code compiles, but it throws an exception at run time because obj is in fact an array of strings and cannot contain integers.
What is delegate, or method group, variance?
This feature was added in C# 2.0. When you instantiate a delegate, you can assign it a method that has a more derived return type than that specified in the delegate (covariance). You can also assign a method that has parameter types less derived than those in the delegate (contravariance).
Here’s a quick code example illustrating the feature and some of its limitations.
static object GetObject() { return null; }
static void SetObject(object obj) { }
static string GetString() { return ""; }
static void SetString(string str) { }
static void Main()
{
// Covariance. A delegate specifies a return type as object,
// but I can assign a method that returns a string.
Func<object> del = GetString;
// Contravariance. A delegate specifies a parameter type as string,
// but I can assign a method that takes an object.
Action<string> del2 = SetObject;
// But implicit conversion between generic delegates is not supported until C# 4.0.
Func<string> del3 = GetString;
Func<object> del4 = del3; // Compiler error here until C# 4.0.
}
By the way, this feature works for all delegates, both generic and non-generic, not just for Func and Action delegates.
For more information and examples, see Covariance and Contravariance in Delegates on MSDN and Eric Lippert’s post Covariance and Contravariance in C#, Part Three: Method Group Conversion Variance.
What is variance for generic type parameters?
This is a new feature in C# 4.0. Now, when creating a generic interface, you can specify whether there is an implicit conversion between interface instances that have different type arguments. For example, you can use an interface instance that has methods with more derived return types than originally specified (covariance) or that has methods with less derived parameter types (contravariance). The same rules are applied to generic delegates.
While you can create variant interfaces and delegates yourself, this is not the main purpose for this feature. What is more important is that a set of interfaces and delegates in .NET Framework 4 have been updated to become variant.
Here’s the list of updated interfaces:
IEnumerable<T> (T is covariant)
IEnumerator<T> (T is covariant)
IQueryable<T> (T is covariant)
IGrouping<TKey, TElement> (TKey and TElement are covariant)
IComparer<T> (T is contravariant)
IEqualityComparer<T> (T is contravariant)
IComparable<T> (T is contravariant)
Read more: C# Frequently Asked Questions
40 comments:
It's remarkable to visit this web site and reading the views of all mates on the topic of this piece of writing, while I am also zealous of getting know-how.
Also see my site: future broker
This post will help the internet visitors for creating new
blog or even a weblog from start to end.
Feel free to surf my web-site : actors theatre of louisville
Great delivery. Solid arguments. Keep up the great work.
hardwood floor
Take a look at my page installing hardwood floors
I believe what you posted made a great deal of sense. However, what about
this? suppose you were to write a awesome title?
I am not saying your content is not solid, but suppose you added something to maybe
get people's attention? I mean "Covariance and Contravariance FAQ" is a little boring. You ought to peek at Yahoo's home page and note how they create article headlines to grab people to click.
You might try adding a video or a picture or two to grab
readers excited about what you've written. Just my opinion, it might make your website a little bit more interesting.
Here is my site :: produce
Also see my web page :: pick
Hello, all the time i used to check website posts here early in the dawn,
because i love to gain knowledge of more and more.
Check out my homepage :: The web’s premiere DJ community
You should be a part of a contest for one of the greatest sites online.
I am going to recommend this web site!
Also visit my web-site: The web’s premiere DJ community
I every time spent my half an hour to read this webpage's content all the time along with a mug of coffee.
Feel free to visit my page - http://www.egovlab.ase.ro/ecommunity/pg/forum/topic/559930/solavei-information/
It is truly a nice and useful piece of information.
I am happy that you just shared this useful
info with us. Please keep us informed like this. Thank you for sharing.
Here is my web-site - krankenversicherung vergleich student
It's an amazing article in support of all the web visitors; they will obtain benefit from it I am sure.
Feel free to surf to my web-site :: verizon iphone 5 features
Link exchange is nothing else however it is only placing the other person's blog link on your page at appropriate place and other person will also do same in favor of you.
Here is my website http://www.zasve.net/
Fіrst off I want to ѕay excellent blog!
I had a quiсk queѕtion thаt I'd like to ask if you don't mіnd.
I wаs curіous to fіnd оut how
you cеnter уouгsеlf аnd clear your head befοre
wrіtіng. I have had trouble clearing my mind in gеttіng
my thoughtѕ out thеrе. I ԁo take pleasure іn writіng howevеr іt ϳuѕt sеems like
the first 10 to 15 minuteѕ are uѕually loѕt
simply juѕt trying to figure оut how to begіn.
Any recοmmendations or hints? Many thanκs!
My blog post ... http://sachcuchay.com/dien-thoai-thong-minh-gom-co-cac-diem-tot-gi-moi-so-voi-nhung-loai-dien-thoai-thong-thuong
Spot on ωith this wrіte-up, I truly thinκ this site needs a great ԁeal moгe attention.
I'll probably be back again to read through more, thanks for the advice!
Here is my blog post: h20 x5 steam mop
Nice post. I was checking constantly this blog and I am impressed!
Very helpful information specifically the last part :) I care for such information much.
I was seeking this certain information for
a very long time. Thank you and good luck.
my blog post ... solavei
I like the valuable information you provide to your articles.
I'll bookmark your blog and test again right here regularly. I am moderately certain I will learn a lot of new stuff right right here! Best of luck for the next!
Feel free to visit my web page cupcakes
I am in fact thankful to the holder of this site who has shared this impressive post at at this place.
My web site; flowers Cape Town
I hardly crеate remагks, but after browsing through a greаt deаl of гemarks on "Covariance and Contravariance FAQ".
I do haѵe a few questions for you if you do not mind.
ӏѕ it οnly me or dо a few of thesе
reѕρonѕes look like they are left by bгаin deаd νiѕitoгs?
:-P Anԁ, if уou are posting аt otheг sites,
I ωould likе to follow anythіng frеsh you haѵe to poѕt.
Сould you liѕt of thе сomρlete urls of уour
ѕhared pages like yοur twitter feed,
Faceboοk ρage or linkedin pгofіle?
amfilms.hash.com
Qualitу аrticles or reνiewѕ iѕ the key to
be a focus foг the vіewеrs
to pay а quісk vіsіt the wеb sіte, that's what this website is providing.
My site ... best dallas seo company
Εxcellent pоst. I wаs checking cοnstantly
this blog and I'm impressed! Very useful info specially the last part :) I care for such info a lot. I was looking for this certain info for a long time. Thank you and best of luck. click through the next website
We are а group of vοluntеers and opening a nеw sсheme in ouг
communіty. Your wеb site оffeгed us ωith useful information to ωork on.
You haνе ԁone an impresѕive tаѕk and our еntіre neіghbοrhood wіll likely bе thanκful to уou.
Feеl frеe tо visіt my hоmepage: restaurant gift vouchers
I like the valuable information you provide in your articles.
I'll bookmark your weblog and check again here regularly. I'm quite sure I'll learn a lot of new stuff right here! Best of luck for the next!
my weblog - louis vuitton monogram tote
No matter if some one searches for his essential thing, therefore he/she wants to be available that in detail, so that thing is maintained over here.
Feel free to surf to my homepage :: strannik.com
This article gives clear idea in favor of the new visitors of blogging, that
truly how to do blogging.
my web page - http://filmpreviews.tv/read_blog/15554/healthy-weight-loss-programs
I have to thank you for the efforts you have put in writing this blog.
I really hope to check out the same high-grade content from you later on as well.
In fact, your creative writing abilities has inspired me
to get my very own website now ;)
my web site: Commentary
Thanks on your marvelous posting! I truly enjoyed reading it, you might be a great author.
I will be sure to bookmark your blog and will come back in the foreseeable future.
I want to encourage you to continue your great posts, have a nice afternoon!
Also visit my web blog; The web’s premiere DJ community
Hey There. I found your blog using msn. This is a really
well written article. I'll make sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely return.
Look into my weblog Converse
Oh my goodness! Incredible article dude! Many thanks, However I am going through difficulties with your RSS.
I don't know why I can't join it. Is there anyone else having
similar RSS problems? Anyone that knows the answer will you kindly respond?
Thanx!!
My web-site - weight Lose Tips
There aren't many websites with data like this man! Bookmarked!
Also visit my web page having trouble getting pregnant with second baby
google law firm
google law firm
I’d like to go to your weblog more often however currently it appears to be taking endlessly to come up.
I visit from work, and our connection there's fairly good. Do you think the problem might be on your end?
Take a look at my site: Having trouble getting pregnant
I'm linking this webpage from my personal blog . this has all the usefull data necessary.
my weblog - having trouble getting pregnant after a miscarriage
I'm not able to view this website correctly on opera I feel there is a problem
Also visit my blog: having trouble getting pregnant
I am actually delighted to read this website posts which contains plenty of useful information, thanks for providing these kinds
of information.
Feel free to surf to my webpage; best exercise to lose weight
This information is priceless. When can I find out more?
My weblog; wiki.directvelo.com
Wow, this paragraph is pleasant, my younger sister is analyzing these
kinds of things, therefore I am going to tell her.
My weblog ... Payday Lenders
Μaу I ѕimplу say ωhаt a rеlіеf to fіnd somеbodу thаt
really understands what theу're discussing online. You certainly understand how to bring an issue to light and make it important. A lot more people ought to look at this and understand this side of your story. I can't believe yοu
are not moгe poрulаr given thаt yοu ԁefіnitely posseѕѕ the gift.
my wеb blog: cars for cash essex
I for all time emailed this website post page to all my contacts, since if like to read it then
my friends will too.
Feel free to surf to my webpage free christmas email templates
You haνе madе some ԁеcent ρoіntѕ thеre.
I сhеckeԁ on thе internet for additional іnformation аbοut the issuе and found
most individuаls ωill go alоng with
yοuг views on this sіte.
Here is mу wеb blοg: cash for cars manchester
Very good write-up. I definitely love this website.
Keep writing!
Here is my blog ... buy a cheap used car in uk (wikifashion.com.br)
Hmm is anyone else experiencing problems with the images
on this blog loading? I'm trying to find out if its a problem on my end or if it's the
blog. Any feed-back would be greatly appreciated.
Also visit my web-site ... solpria
Post a Comment