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)

24 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

Post a Comment