Determine if type is dictionary

C#GenericsDictionary

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheun ArbeiderView Question on Stackoverflow
Solution 1 - C#LeeView Answer on Stackoverflow
Solution 2 - C#Ilya IvanovView Answer on Stackoverflow
Solution 3 - C#0b101010View Answer on Stackoverflow
Solution 4 - C#IgarioshkaView Answer on Stackoverflow