I need to get the name of generic-type in form of its declaration in code.
For example: For List<Int32> I want to get string "List<Int32>". Standart property Type.Name returns "List`1" in this situation.
EDIT: example was fixed
Old question, but I only have the need for this today. So I wrote an extension method that can output nice looking C#-formatted generic name that can handle multilevel nested generic types.
using System;
using System.Text;
public static class TypeExtensions
{
public static string GetNiceName(this Type type, bool useFullName = false)
{
if (!type.IsGenericType) {
return type.Name;
}
var typeNameBuilder = new StringBuilder();
GetNiceGenericName(typeNameBuilder, type, useFullName);
return typeNameBuilder.ToString();
}
static void GetNiceGenericName(StringBuilder sb, Type type, bool useFullName)
{
if (!type.IsGenericType) {
sb.Append(useFullName ? type.FullName : type.Name);
return;
}
var typeDef = type.GetGenericTypeDefinition();
var typeName = useFullName ? typeDef.FullName : typeDef.Name;
sb.Append(typeName);
sb.Length -= typeName.Length - typeName.LastIndexOf('`');
sb.Append('<');
foreach (var typeArgument in type.GenericTypeArguments) {
GetNiceGenericName(sb, typeArgument, useFullName);
sb.Append(", ");
}
sb.Length -= 2;
sb.Append('>');
}
}
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