Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic collections type test

I'd like to make some operations according to a given collection type (using reflexion), regardless of the generic type.

Here is my code:

    void MyFct(Type a_type)
    {
        // Check if it's type of List<>
        if (a_type.Name == "List`1")
        {
            // Do stuff
        }
        // Check if it's type of Dictionary<,>
        else if (a_type.Name == "Dictionary`2")
        {
            // Do stuff
        }
    }

It works for now, but it gets obvious to me that it's not the most safe solution.

    void MyFct(Type a_type)
    {
        // Check if it's type of List<>
        if (a_type == typeof(List<>))
        {
            // Do stuff
        }
        // Check if it's type of Dictionary<,>
        else if (a_type == typeof(Dictionary<,>))
        {
            // Do stuff
        }
    }

I tried that too, it actualy compiles but doesn't work... I also tried to test all interfaces of the given collection type, but it implies an exclusivity for interfaces in collections...

I hope I made myself clear, my english lack of training :)

like image 546
s0ubap Avatar asked Apr 27 '12 18:04

s0ubap


People also ask

What are generic collections?

A generic collection is strongly typed (you can store one type of objects into it) so that we can eliminate runtime type mismatches, it improves the performance by avoiding boxing and unboxing.

What is difference between generic and collection?

Since collections never do anything with the objects they store a collection really doesn't have to know anything about the object. So every type is allowed. With Generics this is a lot easier. We have collections containing only strings, only integers, only your own custom class type.

Are generic collections type-safe?

Generic Classes or Generic Collection Type safe means we will declare the data type of the data, which list will hold it at the time of its initialization. Thus, it will contain only one type of data.


1 Answers

If you want to see if something implements a specific generic type, then you would need to do this:

if(a_type.IsGenericType && a_type.GetGenericTypeDefinition() == typeof(List<>))

The GetGenericTypeDefinition() method will return the unbounded generic type for you test against.

like image 50
Tejs Avatar answered Sep 26 '22 19:09

Tejs