views:

985

answers:

3

Hello everybody!

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

+9  A: 

You can use: typeof(T)

if (typeof(T) == typeof(object) ) {
    // Check for IEnumerable
}
Keith
+15  A: 

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).

Marc Gravell
I agree with this. It's the cleanest way to do it
Isak Savo
Thank you very much! I will do it that way.
Mil
A: 

If you want to use the is operator in a generic class/method you have to limit T to a reference type:

public void MyMethod<T>(T theItem) where T : class
{
    if (theItem is IEnumerable) { DoStuff(); }
}
Isak Savo
I think he's just concerned when an non-generic IEnumerable is passed as a System.Object when T is System.Object
Mark Cidade
marxidad, yes, that's right.
Mil