Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 612
AwkwardCoder Avatar asked May 09 '13 16:05

AwkwardCoder


1 Answers

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;
}
like image 177
Kirk Woll Avatar answered Sep 24 '22 10:09

Kirk Woll