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)
if (names.Contains((string)sqlCommand.ExecuteScalar())
(I discovered this issue in my StringListConstraint for ASP.Net MVC)


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


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:

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.

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

Post a Comment