KentZhou
KentZhou

Reputation: 25553

How to detect if collection contain instance of specific type?

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?

Upvotes: 7

Views: 3926

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564323

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.

Upvotes: 10

Related Questions