Today I’ve faced with task to convert variable of type Type (wich can be generic) into string exression. For example, I have such variable:
Type someType = typeof(Dictionary);
and I need to have C#-string representation of this type as follows: “Dictionaнy<Int32,String>“. Quite useful during T4-templates generation.
Here is small code snippet for that:
public class GenericTypeFormatter
{
private const char GenericTypeParameterPrefix = '<';
private const char GenericTypeParameterSuffix = '>';
public static string GenericTypeToString(Type type)
{
if (!type.IsGenericType) return type.Name;
Type[] args = type.GetGenericArguments();
StringBuilder joinedTypeArgs = new StringBuilder();
foreach (Type t in args)
{
if (joinedTypeArgs.Length > 0) joinedTypeArgs.Append(",");
joinedTypeArgs.Append(GenericTypeToString(t));
}
return
type.GetGenericTypeDefinition().Name.Replace("`" + args.Length, "") +
GenericTypeParameterPrefix +
joinedTypeArgs +
GenericTypeParameterSuffix;
}
}