Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitive Dictionary not working

I have spend a couple of hours trying to figure out why my generic Dictionary(Of String, String) is not ignoring case.

Here is my code:

Dim test As New System.Collections.Generic.Dictionary(Of String, String)(System.StringComparison.OrdinalIgnoreCase)
test.Add("FROG", "1")
Console.WriteLine(test.ContainsKey("frog"))

The console shows "False" every time. It should be showing "True".

If I use:

Console.WriteLine(test."frog")) 

I get a KeyNotFoundException.

It seems as if the Comparer parameter is being completely ignored.

What is going on?

like image 396
Michael Rodrigues Avatar asked Jun 15 '11 02:06

Michael Rodrigues


1 Answers

As hinted here, it's a simple spelling mistake.

The issue is System.StringComparison.OrdinalIgnoreCase is an Integer Enum.
It should be System.StringComparer.OrdinalIgnoreCase

New System.Collections.Generic.Dictionary(Of String, String)(System.StringComparison.OrdinalIgnoreCase) is actually calling the New(capacity As Integer) overloaded constructor, and passing 5.

So, to make it all work as expected, the instantiation line should read:

Dim test As New System.Collections.Generic.Dictionary(Of String, String)(System.StringComparer.OrdinalIgnoreCase)
like image 162
Michael Rodrigues Avatar answered Sep 22 '22 05:09

Michael Rodrigues