tags:

views:

65

answers:

1

Suppose I create collection like

Collection<IMyType> coll;

Then I have many implelentations of IMyTypem like, T1, T2, T3...

Then I want know if the collection coll contains a instance of type T1. So I want to write a method like

public bool ContainType( <T>){...}

here the param should be class type, not class instance. How to write code for this kind of issue?

+4  A: 

You can do:

 public bool ContainsType(this IEnumerable collection, Type type)
 {
      return collection.Any(i => i.GetType() == type);
 }

And then call it like:

 bool hasType = coll.ContainsType(typeof(T1));

If you want to see if a collection contains a type that is convertible to the specified type, you can do:

bool hasType = coll.OfType<T1>().Any();

This is different, though, as it will return true if coll contains any subclasses of T1 as well.

Reed Copsey
+1 for avoiding looping and for using lambda.
ydobonmai
Thank you very much.
KentZhou
Then, How to call this method? Coll.COntainsType(T1)? it is not accepted in VS. I got error said: 'T1' is a 'type' but is used like a 'variable'
KentZhou
Thanks. will try.
KentZhou
It's woking fine. Thanks.
KentZhou