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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With