Ever wanted to know how to determine if an object derives or implements from a collection type?
I figured as all collections I understand in .NET 2.0+ derive unequivocally back to IEnumerable I could test if my object implemented this class.
However after trying a few of my own ideas (the obvious Obj is IEnumerable, Obj is IList), looking around and then asking on Stack Overflow, I could not find an answer and it did not seem as simple as I thought! I did receive a few answers though where people suggested to test implementation of IEnumerable, but none of the code examples seemed to work for me to test a Generic.List of mine with a set of custom objects.
However a late post from s_ruchit returned something so simple:
if(Obj is ICollection)
{
//Derived from ICollection
}
else
{
//Not Derived from ICollection
}
Now I’ve seen that, I would prefer to use IList (obj is IList), as I know it is more applicable to the type I wish to test. But any ideas why my Obj is IEnumerable and Obj is IList did not work for my System.Collections.Generic.List? Very interesting! I’d be happy to hear thoughts. (not like Sylar from Heroes, but I mean.. comments on here.)
4 Comments
if (obj is IList) will call System.Collections.IList and NOT System.Collections.Generic.IList, because you’ll need to provide the type parameter for the generic, i.e.
if (obj is IList)
If that makes sense?
Monty
Wordpress has just taken out my type parameters, trying again:
if (obj is IList[String])
Instead of [, use angle brackets, you know what I mean
@Monty: Yeah you’d probably have to use & lt; without the space to make that work as proper < and >.
@Monty: Hmmm. Well I never know the type, as it was a custom class coming in as “T”, so I don’t know if IList<T> would have worked either. Ah well, past that now, thanks for your comments for the next intrepid adventures to come stumbling by here…. =)
Post a Comment