Adriaan Davel
Adriaan Davel

Reputation: 748

Get Generic Container Type

I need to find out if a Type I'm working with is a Generic 'container', for example if I have a List<int> I need to check if I'm working with a List (I know how to get whether I'm working with an int), how would I do that? (I'm thinking Reflection). Another example, I have a class called StructContainer<T>, I need to find the word (name) 'StructContainer', I'm not too bothered with what 'T' is, using reflection I get StructContainer'1, would hate to have to do some string splitting etc /EDIT: Just to explain further, StructContainer<int> I need 'StructContainer', Tuple<int> I need 'Tuple', List<int> I need 'List' and so forth

Upvotes: 0

Views: 764

Answers (2)

Dean Chalk
Dean Chalk

Reputation: 20461

string type = yourObject.GetType().Name.Split('`')[0];

Upvotes: -1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

Your first question can be achieved in multiple ways:

  1. Check whether your object implements IEnumerable<T>: yourObject is IEnumerable<int>. This only works if you know the type of the object in the container (int in this case)
  2. Use the same solution I described below, just change StructContainer to List.

As to your second question, you can do this:

var yourObject = new StructContainer<int>();
var yourType = yourObject.GetType();
if(yourType.IsGenericType &&
   yourType.GetGenericTypeDefinition() == typeof(StructContainer<>))
    // ...

Upvotes: 4

Related Questions