Hostile to friendly type names

Have you ever written some code that dumps type names using reflection and run into annoyances like this?

Query
new[]
{
    typeof(List<int>),
    typeof(List<List<int>>),
    typeof(int?),
    typeof(bool),
}.Select(t => t.Name).Dump("hostile type names");
Output

image

 

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<int>),
    typeof(List<List<int>>),
    typeof(int?),
    typeof(bool),
}
.Select(t => new
{    
    HostileName = t.Name,
    FriendlyName = t.GetFriendlyName()
})
.Dump("hostile -> friendly type names");
Output

image

 
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);
        }
    }
}
Posted in .NET, C#. 4 Comments »
Follow

Get every new post delivered to your Inbox.