I am working on code generation and ran into a snag with generics. Here is a \"simplified\" version of what is causing me issues.
Dictionary
This evening I was toying a bit with extension methods and I tried to find an answer for your question. Here is the result: it's a no-warranty code. ;-)
internal static class TypeHelper
{
private const char genericSpecialChar = '`';
private const string genericSeparator = ", ";
public static string GetCleanName(this Type t)
{
string name = t.Name;
if (t.IsGenericType)
{
name = name.Remove(name.IndexOf(genericSpecialChar));
}
return name;
}
public static string GetCodeDefinition(this Type t)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}.{1}", t.Namespace, t.GetCleanName());
if (t.IsGenericType)
{
var names = from ga in t.GetGenericArguments()
select GetCodeDefinition(ga);
sb.Append("<");
sb.Append(string.Join(genericSeparator, names.ToArray()));
sb.Append(">");
}
return sb.ToString();
}
}
class Program
{
static void Main(string[] args)
{
object[] testCases = {
new Dictionary(),
new List(),
new List>(),
0
};
Type t = testCases[0].GetType();
string text = t.GetCodeDefinition();
Console.WriteLine(text);
}
}