Determine if type is dictionary [duplicate]

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.


Solution 1:

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];

Solution 2:

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.

Solution 3:

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<,>))

Solution 4:

how about

Dictionary<string, object> d = new Dictionary<string, object>();
Dictionary<int, string> d2 = new Dictionary<int, string>();
List<string> d3 = new List<string>();

Console.WriteLine(d is System.Collections.IDictionary);
Console.WriteLine(d2 is System.Collections.IDictionary);
Console.WriteLine(d3 is System.Collections.IDictionary);

as all generic Dictionary types inherit from IDictionary interface, you may just check that