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?
You can use the non-generic interface types, or if you really need to know that the collection is generic you can use
typeofwithout type arguments.For good measure, you should check
obj.GetType().IsGenericTypeto avoid anInvalidOperationExceptionfor non-generic types.