Reputation: 42260
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?
Upvotes: 5
Views: 4240
Reputation: 4485
Here is some boolean functions that work with generic interface types in vb.net framework 2.0:
Public Shared Function isList(o as Object) as Boolean
if o is Nothing then return False
Dim t as Type = o.GetType()
if not t.isGenericType then return False
return (t.GetGenericTypeDefinition().toString() = "System.Collections.Generic.List`1[T]")
End Function
Public Shared Function isDict(o as Object) as Boolean
if o is Nothing then return False
Dim t as Type = o.GetType()
if not t.isGenericType then return False
return (t.GetGenericTypeDefinition().toString() = "System.Collections.Generic.Dictionary`2[TKey,TValue]")
End Function
Upvotes: 0
Reputation: 57919
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.
Upvotes: 4
Reputation: 99
private void CheckType(object o)
{
if (o is IDictionary)
{
Debug.WriteLine("I implement IDictionary");
}
else if (o is IList)
{
Debug.WriteLine("I implement IList");
}
}
Upvotes: 9
Reputation: 6434
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.
Upvotes: 1