C# Get Generic Type Name

You can implement an extension method to get the “friendly name” of a type, like this:

public static class TypeNameExtensions
{
    public static string GetFriendlyName(this Type type)
    {
        string friendlyName = type.Name;
        if (type.IsGenericType)
        {
            int iBacktick = friendlyName.IndexOf('`');
            if (iBacktick > 0)
            {
                friendlyName = friendlyName.Remove(iBacktick);
            }
            friendlyName += "<";
            Type[] typeParameters = type.GetGenericArguments();
            for (int i = 0; i < typeParameters.Length; ++i)
            {
                string typeParamName = GetFriendlyName(typeParameters[i]);
                friendlyName += (i == 0 ? typeParamName : "," + typeParamName);
            }
            friendlyName += ">";
        }

        return friendlyName;
    }
}

With this in your project, you can now say:

MessageBox.Show(t.GetFriendlyName());

And it will display “List<String>”.

I know the OP didn’t ask for the generic type parameters, but I prefer it that way. 😉

Namespaces, standard aliases for built-in types, and use of StringBuilder left as an exercise for the reader. 😉

Leave a Comment