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?
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With