Search code examples
c#.netreflection

Get user-friendly name for generic type in C#


Is there an easy way without writing a recursive method which will give a 'user friendly' name for a generic type from the Type class?

E.g. For the following code I want something like 'List<Dictionary<Int>>' instead of the shorthand or full name given by the following code:

var list = new List<Dictionary<int, string>>();
var type = list.GetType();

Console.WriteLine(type.Name);
Console.WriteLine(type.FullName);

Solution

  • Based on your edited question, you want something like this:

    public static string GetFriendlyName(this Type type)
    {
        if (type == typeof(int))
            return "int";
        else if (type == typeof(short))
            return "short";
        else if (type == typeof(byte))
            return "byte";
        else if (type == typeof(bool)) 
            return "bool";
        else if (type == typeof(long))
            return "long";
        else if (type == typeof(float))
            return "float";
        else if (type == typeof(double))
            return "double";
        else if (type == typeof(decimal))
            return "decimal";
        else if (type == typeof(string))
            return "string";
        else if (type.IsGenericType)
            return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x)).ToArray()) + ">";
        else
            return type.Name;
    }