Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection - Getting the generic arguments from a System.Type instance

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?

like image 672
driis Avatar asked Nov 16 '08 14:11

driis


People also ask

What is generic type arguments?

The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.

How do you call a generic using reflection?

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod: MethodInfo method = typeof(Sample). GetMethod(nameof(Sample. GenericMethod)); MethodInfo generic = method.

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.


2 Answers

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 
like image 153
Jon Skeet Avatar answered Sep 25 '22 13:09

Jon Skeet


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

like image 41
Hans Passant Avatar answered Sep 25 '22 13:09

Hans Passant