Reputation: 2814
I have a generic function that returns a Dictionary. If the key of the Dictionary is a string, I want to use the String.OrdinalIgnoreCase comparer.
This is my code:
public static Dictionary<K,V> getDict<K,V>()
{
Dictionary<K,V> aDict;
if(typeof(K)==typeof(string))
{
var stringDict = new Dictionary<string, V>(StringComparer.OrdinalIgnoreCase);
aDict = (Dictionary<K,V>)stringDict; // error here - can't convert.
}
else aDict = new Dictionary<K, V>();
// do more stuff here
return aDict;
}
However it tells me it
can't convert a
Dictionary<string,V>
to aDictionary<K,V>
.
How should I be doing this?
Upvotes: 0
Views: 75
Reputation: 15794
This should work the best for you:
var stringDict = new Dictionary<K, V>(
StringComparer.OrdinalIgnoreCase as IEqualityComparer<K>);
The problem is that the Dictionary<TKey,TValue>
ctor expects an IEqualityComparer<T>
. StringComparer
gives you an IEqualityComparer
- the non-generic variety. Once you cast your equality comparer correctly, you should be on your way.
Test code block below will trigger the expected exception:
var dict = getDict<string, int>();
dict.Add("alpha", 1);
dict.Add("Alpha", 2); // triggers the expected duplicate key exception.
HTH...
Upvotes: 2
Reputation: 100630
One common solution - cast through intermediate cast to object
:
aDict = (Dictionary<K,V>)(object)stringDict;
Upvotes: 1