I am trying to make Dictionary case insensitive. But, I declare it as a property, how can I make that insensitive.
I know that while defining, I can use it like :
var dict = new Dictionary<string, YourClass>(
StringComparer.InvariantCultureIgnoreCase);
But, I am defining it in my interface and class respectively like
IDictionary<string, string> dict { get; }
public Dictionary<string, string> dict { get; set; }
How can I make this case insensitive ?
You mentioned that You define it in Your class like:
public Dictionary<string, string> dict { get; set; }
So, instead of using short form for auto properties, use the full form:
Dictionary<string, string> _dict = new Dictionary<string, string>(
StringComparer.InvariantCultureIgnoreCase);
public Dictionary<string, string> dict
{
get { return _dict; }
set { _dict = value; }
}
If You are using C# 6.0, You could also probably even write it using the new auto property initializers syntax:
public Dictionary<string, string> dict { get; set; } = new Dictionary<string, string>(
StringComparer.InvariantCultureIgnoreCase);
Links:
The only way you could enforce it on the class or interface level is you make a new derived type and use that type.
public class CaseInsensitiveDictionary<TValue> : Dictionary<string, TValue>
{
public CaseInsensitiveDictionary() : base(StringComparer.InvariantCultureIgnoreCase)
{
}
}
Then in your interface you would do
CaseInsensitiveDictionary<YourClass> { get; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With