Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: How to check the type within a generic typed class?

How do I get the type of a generic typed class within the class?

An example:

I build a generic typed collection implementing ICollection< T>. Within I have methods like

    public void Add(T item){
        ...
    }

    public void Add(IEnumerable<T> enumItems){
        ...
    }

How can I ask within the method for the given type T?

The reason for my question is: If object is used as T the collection uses Add(object item) instead of Add(IEnumerable<object> enumItems) even if the parameter is IEnumerable. So in the first case it would add the whole enumerable collection as one object instead of multiple objects of the enumerable collection.

So i need something like

if (T is object) {
    // Check for IEnumerable
}

but of course that cannot work in C#. Suggestions?

Thank you very much!

Michael

like image 773
Mil Avatar asked Oct 24 '08 11:10

Mil


2 Answers

You can use: typeof(T)

if (typeof(T) == typeof(object) ) {
    // Check for IEnumerable
}
like image 98
Keith Avatar answered Oct 18 '22 02:10

Keith


Personally, I would side step the issue by renaming the IEnumerable<T> method to AddRange. This avoids such issues, and is consistent with existing APIs such as List<T>.AddRange.

It also keeps things clean when the T you want to add implements IEnumerable<T> (rare, I'll admit).

like image 40
Marc Gravell Avatar answered Oct 18 '22 01:10

Marc Gravell