Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get GenericType-Name in good format using Reflection on C#

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

like image 616
AndreyAkinshin Avatar asked Oct 07 '09 17:10

AndreyAkinshin


1 Answers

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('>');
    }
}
like image 184
Amry Avatar answered Oct 24 '22 11:10

Amry