Mil
Mil

Reputation: 756

.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

Upvotes: 15

Views: 9913

Answers (3)

Isak Savo
Isak Savo

Reputation: 35884

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(); }
}

Upvotes: -1

Marc Gravell
Marc Gravell

Reputation: 1062502

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

Upvotes: 22

Keith
Keith

Reputation: 155602

You can use: typeof(T)

if (typeof(T) == typeof(object) ) {
    // Check for IEnumerable
}

Upvotes: 32

Related Questions