38

If I have the following code:

MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();

How can I find out which type argument(s) "anInstance" was instantiated with, by looking at the type variable? Is it possible?

Ulf Ã…kerstedt
  • 3,086
  • 4
  • 26
  • 28
driis
  • 161,458
  • 45
  • 265
  • 341

2 Answers2

62

Use Type.GetGenericArguments. For example:

using System;
using System.Collections.Generic;

public class Test
{
    static void Main()
    {
        var dict = new Dictionary<string, int>();

        Type type = dict.GetType();
        Console.WriteLine("Type arguments:");
        foreach (Type arg in type.GetGenericArguments())
        {
            Console.WriteLine("  {0}", arg);
        }
    }
}

Output:

Type arguments:
  System.String
  System.Int32
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
12

Use Type.GetGenericArguments(). For example:

using System;
using System.Reflection;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      MyType<int> anInstance = new MyType<int>();
      Type type = anInstance.GetType();
      foreach (Type t in type.GetGenericArguments())
        Console.WriteLine(t.Name);
      Console.ReadLine();
    }
  }
  public class MyType<T> { }
}

Output: Int32

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536