Have you ever written some code that dumps type names using reflection and run into annoyances like this?
Query
new[]
{
typeof(List),
typeof(List>),
typeof(int?),
typeof(bool),
}.Select(t => t.Name).Dump("hostile type names");
Output
This can be problematic if you are trying to generate C# code via T4 templates or something similar.
A colleague and I recently solved this problem using the C# CodeDom (handy extension method included).
Query
new[]
{
typeof(List),
typeof(List>),
typeof(int?),
typeof(bool),
}
.Select(t => new
{
HostileName = t.Name,
FriendlyName = t.GetFriendlyName()
})
.Dump("hostile -> friendly type names");
Output
Extension method
public static class TypeEx
{
public static string GetFriendlyName(this Type t)
{
using (var provider = new CSharpCodeProvider())
{
var typeRef = new CodeTypeReference(t);
return provider.GetTypeOutput(typeRef);
}
}
}
Comments