I want to generate the name of the generic class with their declared parameter names. For example if I have generic class and instantiated ones like shown below I want to print "MyClass<P1,M>"
.
class MyClass<P1, M1> {}
// ... some code removed here
var myInstance = new MyClass<int,string>();
Now I get my type information for myInstance
and then generic type definition like this:
// MyClass<int,string> type info here
var type = myInstance.GetType();
// MyClass<P1, M1> type info here
var genericType = type.GetGenericTypeDefinition();
Debugger shows genericType
property GenericTypeParameters with all parameter names and type info. However I cannot access that collection from my C# code and casting genericType
to System.RuntimeType class does not work because RuntimeType is internal.
So is there a way to access GenericTypeParameters property somehow or am I SOL here? Environment VS2015, .NET 4.6.1
I think you're just looking for Type.GetGenericArguments
, which you should call on genericType
rather than type
- at that point, the type "arguments" are really the type parameters because it's an open type.
Sample (using Dictionary<,>
for simplicity):
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
var dictionary = new Dictionary<string, int>();
var type = dictionary.GetType();
var genericType = type.GetGenericTypeDefinition();
foreach (var typeArgument in genericType.GetGenericArguments())
{
// TKey, then TValue
Console.WriteLine(typeArgument);
}
}
}
Hopefully with that information you can work out the string formatting etc yourself.
See more on this question at Stackoverflow