Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 714
Theun Arbeider Avatar asked Jun 06 '13 08:06

Theun Arbeider


3 Answers

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];
like image 168
Lee Avatar answered Nov 18 '22 14:11

Lee


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.

like image 30
Ilya Ivanov Avatar answered Nov 18 '22 13:11

Ilya Ivanov


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<,>))
like image 6
0b101010 Avatar answered Nov 18 '22 14:11

0b101010