5

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

5
  • do a_type.ToString(). what does it say? Apr 27, 2012 at 18:04
  • 1
    I suspect you're trying to solve the wrong problem. Adding type-specific checks to generic code is smelly.
    – n8wrl
    Apr 27, 2012 at 18:04
  • * a_type.ToString() => System.Collections.Generic.List`1[MyClass]
    – s0ubap
    Apr 27, 2012 at 18:08
  • @s0ubap: That certainly explains why the test against "List`1" failed
    – n8wrl
    Apr 27, 2012 at 18:09
  • hum.. It actually works; a_type.Name is actually "List`1". I'm just wondering if it's the only solution, which seems "smelly" to me.
    – s0ubap
    Apr 27, 2012 at 18:14

1 Answer 1

9

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.