3

Is it possible to implement a method like

string GetFriendlyName(Type type) { ... }

in .NET that will return the CLR alias of the type, if possible? In this case GetFriendlyName(typeof(Foo)) will return "Foo", but GetFriendlyName(typeof(int)) will return "int" instead of "Int32" like in MemberInfo.Name

Louis Rhys
  • 34,517
  • 56
  • 153
  • 221
  • Those are C# specific aliases not defined by the CLR. It can be confusing to non-C# developers if you display them in another context. – Mike Zboray Mar 18 '13 at 07:11

2 Answers2

6

Well, I don't believe there is no way to do it programmaticly. You can use a dictionary instead of like;

public static readonly Dictionary<Type, string> aliases = new Dictionary<Type, string>()
{
    { typeof(string), "string" },
    { typeof(int), "int" },
    { typeof(byte), "byte" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(ushort), "ushort" },
    { typeof(long), "long" },
    { typeof(uint), "uint" },
    { typeof(ulong), "ulong" },
    { typeof(float), "float" },
    { typeof(double), "double" },
    { typeof(decimal), "decimal" },
    { typeof(object), "object" },
    { typeof(bool), "bool" },
    { typeof(char), "char" }
};

EDIT: I found two questions to provide an answer

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
3

You can try this way :

private string GetFriendlyName(Type type)
{
    Dictionary<string, string> alias = new Dictionary<string, string>()
        {
            {typeof (byte).Name, "byte"},
            {typeof (sbyte).Name, "sbyte"},
            {typeof (short).Name, "short"},
            {typeof (ushort).Name, "ushort"},
            {typeof (int).Name, "int"},
            {typeof (uint).Name, "uint"},
            {typeof (long).Name, "long"},
            {typeof (ulong).Name, "ulong"},
            {typeof (float).Name, "float"},
            {typeof (double).Name, "double"},
            {typeof (decimal).Name, "decimal"},
            {typeof (object).Name, "object"},
            {typeof (bool).Name, "bool"},
            {typeof (char).Name, "char"},
            {typeof (string).Name, "string"}
        };
    return alias.ContainsKey(type.Name) ? alias[type.Name] : type.Name;
}

I suggest you to make alias dictionary static readonly for performance benefit.

Parimal Raj
  • 20,189
  • 9
  • 73
  • 110