tags:

views:

102

answers:

3

Basically I wanna know if all the types in a particular namespace implements a particular interface like IEnumerable.

I know I can do:

foreach type ...
    if type is IEnumerable
        ...

But I don't wanna cast the type just to query if it implements an interface, because the cast will be thrown away either way.

+6  A: 

Using the is operator is not a cast, it is a test, which sounds like what you want. Type casting in C# is done either using the forced casting operator (name?) like so:

((IEnumerable)someCollection)

or the safe casting operator:

someCollection as IEnumerable
JoshJordan
Thanks. Are you sure is isn't casting? I thought it was, because is isn't recommended if you want to use the cast, so AS is better instead of IS first AS after because of double casting AFAIK.
Joan Venge
Actually it's not recommended because "as" first does an "is" check, then performs the cast. So, if you do "is" then "as", you're checking the type twice (effectively doing "is", then "is" again followed by a cast).
lc
Thanks I didn't know that.
Joan Venge
+3  A: 

Assuming I've read you correctly, you want a list of types in an enumeration that implement an particular interface or supertype. Perhaps Enumerable.OfType(this IEnumerable source) is useful?

var enumerables = myListOfThingsToCheck.OfType<IEnumerable>();
lc
Thanks, that's interesting. OfType doesn't care about whether the list is type unsafe? Also is there a version of this to be used on single types outside a collection?
Joan Venge
No list is necessarily "type unsafe" unless it's in an unsafe code block. It might happen to be a list of "System.Object", however, which is exactly what this method was designed for. If you're looking to do this on a single object, just use "is".
lc
Thanks lc. Btw by type safe I meant storing same types vs different types on a list, if it looked different.
Joan Venge
Bear in mind, under the covers, OfType is using the "is" operator to do its thing.
JMarsch
+1  A: 

I think this will work also if you'd rather use lambda syntax.

var enumerables=Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "YOUR NAMESPACE HERE").OfType<IEnumerable>();
Josh Bush