Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an object implements IDictionary or IList of any type

Tags:

c#

.net

Lets say I declare the following

Dictionary<string, string> strings = new Dictionary<string, string>();
List<string> moreStrings = new List<string>();

public void DoSomething(object item)
{
   //here i need to know if item is IDictionary of any type or IList of any type.
}

I have tried using:

item is IDictionary<object, object>
item is IDictionary<dynamic, dynamic>

item.GetType().IsAssignableFrom(typeof(IDictionary<object, object>))
item.GetType().IsAssignableFrom(typeof(IDictionary<dynamic, dynamic>))

item is IList<object>
item is IList<dynamic>

item.GetType().IsAssignableFrom(typeof(IList<object>))
item.GetType().IsAssignableFrom(typeof(IList<dynamic>))

All of which return false!

So how do i determine that (in this context) item implements IDictionary or IList?

like image 683
Matthew Layton Avatar asked Nov 02 '12 16:11

Matthew Layton


3 Answers

    private void CheckType(object o)
    {
        if (o is IDictionary)
        {
            Debug.WriteLine("I implement IDictionary");
        }
        else if (o is IList)
        {
            Debug.WriteLine("I implement IList");
        }
    }
like image 167
AshMeth Avatar answered Oct 23 '22 04:10

AshMeth


You can use the non-generic interface types, or if you really need to know that the collection is generic you can use typeof without type arguments.

obj.GetType().GetGenericTypeDefinition() == typeof(IList<>)
obj.GetType().GetGenericTypeDefinition() == typeof(IDictionary<,>)

For good measure, you should check obj.GetType().IsGenericType to avoid an InvalidOperationException for non-generic types.

like image 30
Jay Avatar answered Oct 23 '22 03:10

Jay


Not sure if this is what you'd want but you could use the GetInterfaces on the item type and then see if any of the returned list are IDictionary or IList

item.GetType().GetInterfaces().Any(x => x.Name == "IDictionary" || x.Name == "IList")

That should do it I think.

like image 32
LukeHennerley Avatar answered Oct 23 '22 03:10

LukeHennerley