How can I determine if Type is of Dictionary<,>
Currently the only thing that worked for me is if I actually know the arguments.
For example:
var dict = new Dictionary<string, object>();
var isDict = dict.GetType() == typeof(Dictionary<string, object>; // This Works
var isDict = dict.GetType() == typeof(Dictionary<,>; // This does not work
But the dictionary won't always be <string, object>
so how can I check whether it's a dictionary without knowing the arguments and without having to check the name (since we also have other classes that contain the word Dictionary
.
Type t = dict.GetType();
bool isDict = t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>);
You can then get the key and value types:
Type keyType = t.GetGenericArguments()[0];
Type valueType = t.GetGenericArguments()[1];
You can use IsAssignableFrom
to check if type implements IDictionary
.
var dict = new Dictionary<string, object>();
var isDict = typeof(IDictionary).IsAssignableFrom(dict.GetType());
Console.WriteLine(isDict); //prints true
This code will print false for all types, that don't implement IDictionary
interface.
There is a very simple way to do this and you were very nearly there.
Try this:
var dict = new Dictionary<string, object>();
var isDict = (dict.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>))
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