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
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
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); } } }




January 10, 2012 at 11:22 am
like
January 19, 2012 at 2:23 pm
Nice one. I have written all sorts of funky methods to pull out friendly names. I suppose I can go delete it all now
February 2, 2012 at 4:21 am
This just entered our extension library. Many thanks
February 2, 2012 at 8:37 pm
[...] 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 [...]