Thursday, January 17, 2013

Readable type name for generic types

I am working on a messaging subsystem capable of transmiting generic XML messages. A message could possibly be interpreted and deserialized to a concrete type and I try to find a readable and useful way of denoting a type name.

For a simple class like this one

namespace ClassLibrary1
{
    public class Class1
    {
    }
}

what would be the output of

var type = typeof(Class1);
 
Console.WriteLine( type.Name );
Console.WriteLine( type.FullName );
Console.WriteLine( type.AssemblyQualifiedName );

?

Well, the output is

Class1
ClassLibrary1.Class1
ClassLibrary1.Class1, ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKey Token=null

Which one of these would you pick as a public denotation of the type name? My obvious choice was the second one, what was yours?

I was however quite surprised to see that this one

namespace ClassLibrary1
{
    public class GenericClass<T>
    {
 
    }
}

with

var type = typeof(GenericClass<Class1>);
 
Console.WriteLine( type.Name );
Console.WriteLine( type.FullName );
Console.WriteLine( type.AssemblyQualifiedName );

doesn’t look as clean as I expected:

GenericClass`1
ClassLibrary1.GenericClass`1[[ClassLibrary1.Class1, ClassLibrary1, 
   Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
ClassLibrary1.GenericClass`1[[ClassLibrary1.Class1, ClassLibrary1, 
   Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], 
ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

A small disaster I would say. The type itself is denoted nicely but the inner generic type is either not denoted at all (type.Name) or denoted with full information.

It seems that other people have extactly the same problem.

And, surprisingly, the simplest answer is to use .ToString().

var ct = typeof(Class1);
Console.WriteLine( ct.ToString() );
 
var gt = typeof( GenericClass<Class1> );
Console.WriteLine( gt.ToString() );

gives

ClassLibrary1.Class1
ClassLibrary1.GenericClass`1[ClassLibrary1.Class1]
which is exactly what I expect. I hope this is reliable.

No comments: