Search code examples
c#genericsreflectiont4texttemplate

name of class with generic parameters?


I'm trying to generate code for series of generic classes using T4.

I want to know how to get full class name using reflection?

public class Foo<TFirst, TSecond> {}

var type = typeof(Foo<,>);
var name = type.FullName; // returns "Foo`2"

what I want is full name with actual generic parameter names that I've written

"Foo<TFirst, TSecond>"

Note that they are not known type, as I said I'm generating code using T4, so I want to have exact naming to use it for code generations, as an example, inside generic methods.

I tried this answers but they require to pass known type which is not what I want.


Solution

  • You can access the type parameter names by reflection using Type.GetGenericArguments:

    using System;
    
    public class Foo<TFirst, TSecond> {}
    
    class Test
    {
        static void Main()
        {
            var type = typeof(Foo<,>);
            Console.WriteLine($"Full name: {type.FullName}");
            Console.WriteLine("Type argument names:");
            foreach (var arg in type.GetGenericArguments())
            {
                Console.WriteLine($"  {arg.Name}");
            }
        }
    }
    

    Note that that's giving the type parameter names because you've used the generic type definition; if you used var type = typeof(Foo<string, int>); you'd get String and Int32 listed (as well as a longer type.FullName.)

    I haven't written any T4 myself, so I don't know whether this is any use to you - in order to get to Foo<TFirst, TSecond> you'd need to write a bit of string manipulation logic. However, this is the only way I know of to get at the type arguments/parameters.