2

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.

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118

1 Answers1

4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    You have to use `arg.Name` instead of `arg.FullName` it seems, because `arg.FullName` in your sample code returns `null` (while `arg.Name` returns correct name). – Evk Oct 14 '17 at 14:23
  • @Evk: Thanks for spotting that. I'd originally tried with `arg.Name`, and thought I'd change it to `arg.FullName` when I wrote it up, to give the System.String/System.Int32 example. Will fix now! – Jon Skeet Oct 14 '17 at 14:24
  • Oh thanks, I tried `string.Join(" ,", type.GetGenericArguments().Select(t => t.FullName))` too, but because I was using FullName it was returning null. – M.kazem Akhgary Oct 14 '17 at 14:27