Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get source code representation of generic type?

Tags:

c#

generics

I'm trying to get generic type in string I get something more like IL representation, I need the real source representation for emitting it.

Type t = typeof(Stack<string>);

string source = t.Name;        //Stack`1[System.String]
string source = t.ToString();  //System.Collections.Generic.Stack`1[System.String]

I just need:

string source //Stack<string>
like image 680
JDOE Avatar asked Aug 05 '26 00:08

JDOE


1 Answers

I've got this extension method, GetPrettyName(). This is basically it:

public static string GetPrettyName(this Type type)
{
    var retval = type.Name;

    if (type.IsGenericType)
    {
        var genargNames = type.GetGenericArguments().Select(t => GetPrettyName(t));
        var idx = type.Name.IndexOf('`');
        var typename = (idx > 0) ? type.Name.Substring(0, idx) : type.Name;
        retval = String.Format("{0}.{1}<{2}>", type.Namespace, typename, String.Join(", ", genargNames));
    }
    else if (type.IsArray)
    {
        retval = GetPrettyName(type.GetElementType()) + "[]";
    }
    else if (String.IsNullOrEmpty(retval))
    {
        retval = type.Name;
    }

    return retval;
}

It operates recursively on each generic type parameter and builds out the full name in a format that's close to the code representation. It's good enough for our purposes (its just used in logging messages here). It can handle generics and arrays, but does not handle Entity Framework proxies that well.