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 »

4 Responses to “Hostile to friendly type names”

  1. Lee Campbell Says:

    Nice one. I have written all sorts of funky methods to pull out friendly names. I suppose I can go delete it all now :)

  2. Brandon Says:

    This just entered our extension library. Many thanks :)

  3. My Shopping List`1 « Palladium Consulting Says:

    [...] IList<SomeSpecialType> becomes IList`1, not really very useful to anyone. James Miles has the following friendly tip on making those names a little friendlier. It’s an expensive enough trick (about 5μs on my [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: