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?
private void CheckType(object o)
{
if (o is IDictionary)
{
Debug.WriteLine("I implement IDictionary");
}
else if (o is IList)
{
Debug.WriteLine("I implement IList");
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With