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)

64 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

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.

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

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

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.

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

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

토토사이트
배트맨토토프로



I like this website its a master peace ! Glad I found this on google .

스포츠중계
토토사이트


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.

Get USA Import Data; Grow Your Export Import Trade in Customs & 100+ Countries. Connect With 100% Verified Buyers, and Suppliers. Visit our website for more import, export and shipment data.
USA Import Data

Modn.in is one of India’s best online gadget ecommerce portals. Providing best quality products in the online space, it offers the latest range of gadgets like headphones and electronic products at the most reasonable price conveniently at your door step. We believe in providing latest and modern gadgets.

feedhour is an independent news service building up its reputation as the most reliable and accurate news platform. Our platform is Independent of government and commercial concerns, providing consumers with free, accurate, and impartial news in English.

We are a global media and entertainment platform that reflects the thoughts and ideas of today’s women of substance who are powerful, passionate, and nonconformist. We inspire women to explore and experience different dimensions of their world – relationships, self-growth, career, travel, health and social issues. We are about every woman who is proving her mettle to the world, leaving it ‘spellbound.’ On this portal, we celebrate “hermagic.”

Nice blog.. Thanks for sharing this blog... I really like it
FindWyse

One of the most essential mathematical notions in calculus is covariance. The Dark Side of Covariance, on the other hand, describes how it is exploited in the present online dissertation help service. Don covers the area of "quant" trading and how to exploit the vulnerabilities in these sorts of deals in this book. In doing so, he shows his readers how to avoid the "Dark Side" and capitalize on the power of covariance.

it is good to find the best designs. There are people searching for the best ideas that brings the best results for us. When I used the professional essay writers uk

Your article is very helpful! You can also read my blog about The Best papillio sandals to plan your trip and book from papillio sandals in advance to avoid last-minute hassles.

The most informative article!virginia reckless driving penaltyis a legal professionals those who experienced in guiding clients with solution to their legal solution.

trucking accident law firms
The "The Dark Side of Covariance" statement has an intriguing title, clear content, relevance, audience specification, and engaging opening. To effectively engage readers, it is essential to provide context, relevance, audience specification, and a hook or introductory sentence. Additionally, ensuring the content aligns with the title and targeting the intended audience is crucial. Overall, the attention-grabbing title and engaging opening can enhance the impact of the content.

Enterprise SEO, also known as corporate or large-scale SEO, refers to the practice of Enterprise SEO Blog search engine optimization specifically tailored for large organizations or businesses with extensive websites, multiple digital assets, and a wide online presence.

This specialized approach to SEO is designed to address the unique challenges and opportunities

that come with managing and optimizing a vast and complex digital footprint

Exploring the intricate web of life's covariance can be as fascinating as drafting a compelling biography. To capture the essence of a remarkable journey, consider hire a writer for biography – they skillfully weave the threads of experiences into a narrative masterpiece.

โปรโมชั่น pg slot มากมาย เล่นง่ายจ่ายจริง แตกจริง ต้อง pg slot เท่านั้น! เล่นสล็อต พีจีสล็อต เว็บไซต์ตรงผู้ให้บริการเกมสล็อตออนไลน์ชั้นหนึ่ง ทกลอง เล่น ฟรี พร้อมโบนัส

Anyone under the age of 18-to participate the sexual activities are illegal. If you need any legal services please visit our page. sex crime lawyer

Great article! The information you shared here is really useful. I particularly like the product featured in this article. Hope for more content like this! Get information about altkeys AI Keyboard: Revolutionizing Typing Experience here.

Thanks for sharing this informative and wonderful blog.. I really like this blog.
Backup Data
Backup as a Service

Post a Comment