The Dark Side of Covariance

What’s wrong with the following code?

var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
...
if (names.Contains(sqlCommand.ExecuteScalar())

This  code is intended to check whether the result of a SQL query is contained in a case-insensitive collection of names.  However, if you run this code, the resulting check will be case-sensitive.  Why?

As you may have guessed from the title, this is caused by covariance.  In fact, this code will not compile at all against .Net 3.5. 

The problem is that ExecuteScalar() returns object, not string.  Therefore, it doesn’t call HashSet<string>.Contains(string), which is what it’s intending to call (and which uses the HashSet’s comparer).  Instead, on .Net 4.0, this calls the  Enumerable.Contains<object>(IEnumerable<object>, string) extension method, using the covariant conversion from IEnumerable<string> to IEnumerable<object>.  Covariance allows us to pass object to the Contains method of any strongly-typed collection (of reference types).

Still, why is it case-sensitive?  As Jon Skeet points out, the LINQ Contains() method is supposed to call any built-in Contains() method from ICollection<T>, so it should still use the HashSet’s case-insensitive Contains().

The reason is that although HashSet<String> implements ICollection<string>, it does not implement ICollection<object>.  Since we’re calling Enumerable.Contains<object>, it checks whether the sequence implements ICollection<object>, which it doesn’t.  (ICollection<T> is not covariant, since it allows write access)

Fortunately, there’s a simple fix: just cast the return value back to string (and add a comment explaining the problem).  This allows the compiler to call HashSet<string>.Contains(string), as was originally intended.

//Call HashSet<string>.Contains(string), not the
//covariant Enumerable.Contains(IEnumerable<object>, object)
//http://blog.slaks.net/2011/12/dark-side-of-covariance.html
if (names.Contains((string)sqlCommand.ExecuteScalar())
(I discovered this issue in my StringListConstraint for ASP.Net MVC)

60 comments:

Oh! This article has suggested to me many new ideas. I will embark on doing it. Hope you can continue to contribute your talents in this area. Thank you.
lucky patcher

Thanks for sharing this useful information
vex 3

This comment has been removed by the author.

Superb Information, I really appreciated with it. This is fine to read and valuable pro potential, I really bookmark it, pro broaden read gmail sign up . Appreciation pro sharing. I like it.

Talking about codes, this info helped me a lot in college. I used info from https://justbuyessay.com/blog/scholarship-essay and it helped me a lot with writing my scholarship essay about it.

thanks for this sharing. I acknowledge your thoughts.
tutuapp apk

It's really helpful for me.

mONICA

The above article is nice and interesting, thank you willing to share! Greetings success of admin Percetakan Murah Rawamangun Jakarta Timur wish you deign to visit my website, thank you :)

Nice Post thanks for sharing. The only way to bring new customers to your business is to go where your audience is by leaving your comfort zone. This way more efficient marketing can be put to action with a custom logo design at work for building recognition.

We are an Allassignmenthelp provider. Our online mission is one of assignment by high demand with other countries in the United States and gives us a chance to help. Cheap Instant Assignment Help

Law Assignment Writing Services are hard to come across for those in need of Law Research Writing Services and law essay writing services.

QuickBooks gives you reminder feature in the business with finest version of Quickbooks software to manage all financial transactions you can visit our website QuickBooks tech support team provide you the complete information.Quickbooks tech support

QuickBooks is one of the most efficient financial management software that can help business owners to complete and maintain the records of daily accounting and financial transactions Quickbooks Backup

I was skeptical about ordering an essay online just like many other customers contemplating buying anything online. I came across writing help through a normal Google search and decided to order an essay. And I was in shocked, that's good and professional essay. So masterpapers is a trustworthy, legitimate, and highly recommended service as far as my experience goes.

Dear admin, really you are doing a fantastic job by sharing this type of useful information with us.
when I read your all post I think each and every post was so important so for that thank you so much and wish you all the best for the upcoming post.
visit my website: https://www.mcafee.com/activate


Great words, your article is too good delineated that it make us realized about the significance of healthcare especially concerns with mental issues. People are availing the medical benefits utterly and the progress will be enhanced eventually as the time passed by. Top online Dentist in Karachi


Best Assignment Experts has been in the business for more than 10 years now and we have helped a large number of students in those 10 years. We give the best assignment help that can help you to score better evaluations consistently and you will likewise gain so much from our specialists. assignment provider , assignment help melbourne

Biology is your bane and you know you are not going to pursue it as a career option. But in school, it is mandatory to study biology and you have been given the assignment to submit in just a week. Use the services of Help In Homework’s team for biology homework help and rid yourself of the pressure of handling it on your own. Our experts will deliver an exquisitely written assignment that follows the guidelines issued by your teacher and has been custom written for you so that you don’t have to deal with plagiarism issues.

Hey! It’s me, Alan Owen! From The Social Network to Tenet to The Muppets, I have a huge watchlist. Apart from watching movies, I am also a coder and a learner of technology. Readers of blogs get the latest updates related to the technical world too.
mcafee.com/activate
office.com/setup
mcafee.com/activate
norton.com/setup

our interactive whiteboard empowered with sound video highlights permits your tutor to evaluate holes in your arrangement. You can chip away at your pain points and settle the earlier year's inquiry papers. Our tutors likewise help you settle worksheets and can audit your homework. As you thrive under master direction, you will likewise observe an improvement in your evaluations. visit - assignment help australia , assignment help uk

Are you looking to convert your Quicken data to Quickbooks? since Quickbooks has been well known for its exceptional accounting needs, you can check this blog post to learn about the steps that you need to take
converting quicken to quickbooks

Me and my Team were searching for the best VPN for my online business and we came acrossSurfshark VPN review 2021. As interesting as it is we would like to share our honest experience + BEST DEALS

Your website is really cool and this is a great inspiring article.

Assignment Writing Service

This is so fun! What a great idea. Also I love how authentic you seem to be.
vivi winkler



Nice post. I used to be checking constantly this blog and I am impressed! Extremely useful info particularly the ultimate section ๐Ÿ™‚ I take care of such information a lot. I was seeking this certain information for a long time. Thank you and best of luck.
a thing of beauty is a joy forever

Great work! The way you describe your words is the best, very informative. SEO services is now heightening its combustion in Pakistan as majority appear their businesses via online platforms.
Best Social Media Marketing Company

If you are looking for mini-games to relax, or you are looking for games that are both entertaining and exercise some skills for your kids, The Impossible Game will be the best choice. Here you can find hundreds of games that will meet your needs. And they are completely free!

Impressive work, your words on clothing speak the truth and we should be heeding on with them, such information is always helpful and can fall under positivity of the society

men's clothing stores in karachi

You must have arrived here after a long search for the russian mail order bride, and I can assure you that you have arrived at the right place! I found my love through this service; At first I doubted its effectiveness and decided that it was just another fake site, but it is not. All sites with women are certified and the girls are real, so you can pick and choose or discover your ideal girl. Good luck finding your soul mate.


Your words really helped here. It was hard for me to go outdoors even for pasta near me. I really wish to have crossed by it earlier.
fast food deals

moldova brides are among the most attractive ladies in Europe. The majority of females have brown or black eyes, dark hair, and olive complexion. This is the type of lady I wanted to spend my life with. I just came across an intriguing article about mailing brides. I asked about it and discovered that I could interact with Moldovan women. Now that I'm married to a Moldovan woman, we're content. I would recommend this dating strategy to everyone.

Users frequently encounter
Quickbooks error 6000 when attempting to access the company file. It happens when the corporate file is on external storage or when the file permissions are improper. To correct this use Quickbooks file doctor tool.

This comment has been removed by the author.


Intuit developed the Quickbooks tool hub, making it easier than ever to fix common QuickBooks application issues and inconsistencies. QB Tool Hub is a multi-functional asset that contains all of the tools needed to resolve common QuickBooks mistakes, such as File Doctor, QuickBooks Refresher, Condense Data Tool, PDF and Print Repair Tool, and others. This is an all-in-one multipurpose tool for dealing with company file problems, network issues, PDF and printing errors, data corruptions, password reset, and other issues.

We're here to help content writing services seo you grow your company. The second most successful and results-oriented lead creation strategy is content writing.

If you are having problem in e-filing tax, then you should installturbotax com

Nice blog.
Quickbook error 15222 is now resolve if you are faced some issue related this error so you got your easy solution for this error in just few second read this page carefully and follow these step.
Quickbook error 15222

Thank you so much for sharing this blog with us. Quickbooks, an accounting program, is readily available. QuickBooks Error 15241 is one of the most common problems that users face. The problem frequently happens during the download or updating of payroll services.

Hey friend, it is very well written article, thank you for the valuable and useful information you provide in this post. Keep up the good work! FYI, Pet Care adda
Credit card processing, wimpy kid books free
,science a blessing or curse essay

I am happy to be here and this wonderful blog. I have found here lots of important information for my knowledge I need. Thanks for sharing this amazing post. If you want to Recover Forgot Spectrum Email Password please contact roadrunner support team for solution.

Non tracking cat litter is the best thing you can buy for your cat. This cat litter does not stick to the paws of your cat.
best non tracking cat litter

Amazing facts about cat memory in this article. Read this article to know more. do cats remember their owners after being separated

This is the right site for each person who should a couple of plans concerning this point. You see a particularly tremendous store of its essentially hitting to battle with you (not that I really would have to… HaHa). You undeniably put another turn concerning a matter which has been analyzed for an incredibly extended period of time. Shocking stuff, essentially puzzling!
how to delete watch history from facebook


you will need support or suggestions, write me privately.
I interested in your implementation/use case.
the best situs slot terbaik
Togel2win
daftar bo bonanza
Slot gampang menang

์Šคํฌ์ธ ์ค‘๊ณ„
ํ† ํ† ์‚ฌ์ดํŠธ


We absolutely love your blog and find almost all of your post’s to be just what I’m looking for.
Does one offer guest writers to write content for you personally?
I wouldn’t mind publishing a post or elaborating on a number of the subjects you write with regards to here.

Again, awesome web log!

magnificent put up, very informative. I'm wondering why the opposite
experts of this sector don't notice this. You must
continue your writing. I am confident, you have a huge readers' base already!



ํ† ํ† ์‚ฌ์ดํŠธ
ํ† ํ† 

In the shadows of evil, an eminent hero can rise from the ruin of an empire. It's time to open the gates and the battle is now underway. Only one thing will protect this world Mehrunes Dagon as well as the demon Europa Universalis 4 Download Pc game nad PUBG PC Cracked Version with virtualdj cracked Download and bluebeam cracked Download with 4k video downloader license key Free also Best asian horror movies and gemini 2 mac crack for this bulk image downloader cracked Download and bitdefender cracked also airflow Crack In the shadows of evil, an eminent hero can rise from the ruin of an empire. It's time to open the gates and the battle is now underway. Only one thing will protect this world Mehrunes Dagon as well as the demon

Without sacrificing quality or craftsmanship, we develop and curate the now of luxury. zvasti has its finger on the pulse of the fast-paced world of luxury home decor, with fresh collections hand-picked from all around the world.

Thank you so much for providing such information. Keep Posting!
If you are looking for any type of technical support related to your operating system, wifi connection, or broadband light blinking red att, you can contact me and my expert team at Internet Homes.

Wonderful post! Thank you for sharing useful information.
You know for business owners, sometimes it gets frustrating when they send an important email and their screen flashes that there is an outlook send error or outlook not syncing and they can’t get important emails, We provide solutions to such problems. To know more visit below mentioned links.
Outlook email stuck in outbox

why outlook says working offline
outlook email stuck in outbox
outlook send receive error
outlook not syncing

Nice Post. I have been reading here for about an hour. I am a newbie and your success is very much an inspiration for me. If you want to Change Spectrum Email Password please contact our team for instant help.

Opensea Login Your song blew me away, I absolutely loved it. Metamask Extension I felt every word that you spoke and I have replayed Metamask Log in it multiple times because I can’t get enough of it. Thank you. | | Metamask Wallet | Opensea NFT

Post a Comment