Specify generics in .config file
A question from a conversation I had yesterday: How can I specify a generic class as a type in a .NET configuration file?
This scenario is often encountered if you build a pluggable architecture using something like the Service Locator Design Pattern. In which the actual types to instantiate are specified in the configuration file.
The issue arise because .NET config files are XML files and the syntax for generics (C#) is MyClass<Type> - angle brackets are "taken". The way this is solved is by introducing an square bracket syntax, in which the type would be written MyClass'1[[Type]].
Likewise the type System.Collections.Generic.List<String> translates to System.Collections.Generic.List'1[[System.String]]
The generic type should be followed by 'N, with N specifying the number of type parameters. So MyClass<A,B> would translate to MyClass'2[[A],[B]]
If you can't figure this out write a simple console application with the statement: System.Console.WriteLine(T.GetType().FullName);
This will write your type T as it should be written in a config file. (note that the types can be fully qualified with version, culture, public key etc.)
Example: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
MyGen<A1,...,AN> becomes MyGen'N[[A1],...,[AN]]
That's it really...
Comments
- Anonymous
April 11, 2007
Thanks for the tip. This was exactly what I was needing in my project. One thing that tripped me up momentarily: my generic class and my T class were coming from different non-strongly-named assemblies, and I had to specify the assembly for both types like so. The last paragraph of your article tipped me off to that. <element type="Namespace1.GenericClass'1[[Namespace2.Class, Assembly2]], Assembly1" />