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?
To determine whether an object is a specific type, you can use your language's type comparison keyword or construct.
The contains() method is used to check if a particular value exists.
The Collection. contains() method check if a collection contains a given object, using the . equals() method to perform the comparison. Returns true if this collection contains the specified element.
This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With