When working in ASP.NET, we often make use of the powerful Dictionary class, which is one of the most awesome ways - although not always the most efficient one - to handle key-value pairs of (almost) any sort. When using a String object as key, we often want it to be case-sensitive, so we can store different items in the following way:
1 2 3 4 |
var Dict = new Dictionary<string,string>(); Dict["Romeo"] = "A stupid cat"; Dict["romeo"] = "A different (yet still stupid) cat"; Dict["ROMEO"] = "A third (nonetheless stupid) cat". |
And so on. This is nothing less than the Dictionary class default behavior: if we stick to the above example we'll have three different entries, each one accessible with their specific, case-sensitive string.
This might or might not be convenient, depending on our specific scenario. Whenever we need the key to be case-insensitive, we can do that by adding a StringComparer to the constructor method in the following way:
1 2 3 4 |
var Dict = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase); Dict["Romeo"] = "A stupid cat"; Dict["romeo"] = "The same stupid cat"; // it overwrites the previous entry. Dict["ROMEO"] = "Still the same stupid cat". // it overwrites the previous entry. |
The above dictionary will have one single entry, which we can get by using its case-insensitive key.
We should be also aware of the fact that, as stated in this StackOverflow thread, using StringComparer.OrdinalIgnoreCase will give you better performance than using StringComparer.InvariantCultureIgnoreCase, assuming we simply need to disregard the case of characters.
That's about it: happy coding!