Darkzaelus
Darkzaelus

Reputation: 2095

C# reflect type with variable number of type parameters

Is it possible to get at run time the type of a generic class that has a variable number of type parameters?

I.e., based on a number, can we get the type of a tuple with this number of elements?

Type type = Type.GetType("System.Tuple<,>");

Upvotes: 2

Views: 929

Answers (2)

Ludwo
Ludwo

Reputation: 6183

Try this:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;

public class MainClass 
{
    public static void Main()
    {
        PrintTypeParams(typeof(Tuple<int, double, string>));
    }

    private static void PrintTypeParams(Type t)
    {
        Console.WriteLine("Type FullName: " + t.FullName);
        Console.WriteLine("Number of arguments: " + t.GetGenericArguments().Length);
        Console.WriteLine("List of arguments:");
        foreach (Type ty in t.GetGenericArguments())
        {
            Console.WriteLine(ty.FullName);
            if (ty.IsGenericParameter)
            {
                Console.WriteLine("Generic parameters:");
                Type[] constraints = ty.GetGenericParameterConstraints();
                foreach (Type c in constraints)
                Console.WriteLine(c.FullName);
            }
        }
    }
}

Output:

 Type FullName: System.Tuple`3[[System.Int32, mscorlib, Version=4.0.0.0, Culture=
 neutral, PublicKeyToken=b77a5c561934e089],[System.Double, mscorlib, Version=4.0.
 0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib,
 Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
 Number of arguments: 3
 List of arguments:
 System.Int32
 System.Double
 System.String

Upvotes: 0

Salvatore Previti
Salvatore Previti

Reputation: 9080

The way to write that is

Type generic = Type.GetType("System.Tuple`2");

The format of generic types is simple:

"Namespace.ClassName`NumberOfArguments"

` is character 96. (ALT+96).

However i would avoid using strings, it is slower than using typeof, or better, an array lookup. I would provide a nice static function that is thousand of times faster...

private static readonly Type[] generictupletypes = new Type[]
{
    typeof(Tuple<>),
    typeof(Tuple<,>),
    typeof(Tuple<,,>),
    typeof(Tuple<,,,>),
    typeof(Tuple<,,,,>),
    typeof(Tuple<,,,,,>),
    typeof(Tuple<,,,,,,>),
    typeof(Tuple<,,,,,,,>)
};

public static Type GetGenericTupleType(int argumentsCount)
{
    return generictupletypes[argumentsCount];
}

Upvotes: 6

Related Questions