[.net] Serializing generic classes

Started by
2 comments, last by JonasB 17 years, 4 months ago
I need to write my own XmlSerializer, and I have problems handling generics. How can I find the types used by a generic type? And how can I instantiate a generic class with specified types? E.g. if I have an instance of List<Sprite>, how do I "get" that it's typed for Sprite? And, when deserializing, if I know that it's a List<> of Sprite, how do I instantiate it? (I don't even know what to google for, I'm just finding very basic generics info) Thanks!
Advertisement
This should provide all the information you need to figure out what type a generic class is created with. (Edit: the msdn site nukes the direct link to the section ... just click on the "Generics and Reflection" link)

For instantiation, I'd look at the Activator.CreateInstance<T> method :-)
Joel Martinez
http://codecube.net
[twitter]joelmartinez[/twitter]
You might use code like this to get generic arguments:
Dictionary<string, int> list = new Dictionary<string, int>();            Type typ = list.GetType();            if (typ.IsGenericType)            {                Type[] args = typ.GetGenericArguments();                Console.WriteLine("Generic Arguments are: {0}, {1}", args[0], args[1]);            }


This URL might have some useful information: Reflection and Generic Types
Thanks guys, that did it! Just in case anyone should have the same problem:

//To serialize:
Type genericType = instanceToSerialize.GetType();
Type genericBase = genericType.GetGenericTypeDefinition();
Type[] typeArgs = genericType.GetGenericArguments();

//serialize / deserialize genericBase.Name and typeArgs names
string[] typeArgsNames = ... //create an array with typeArgs type names
string genericBaseName = genericBase.Name

//To construct instance:

//Note: GetType() uses a LUT to find types in all loaded assemblies
Type[] XtypeArgs = ...//loop through typeArgsNames and GetType()
Type XgenericBase = GetType(genericBaseName);
Type XgenericType = XgenericBase.MakeGenericType(XtypeArgs);
object XinstanceToSerialize = Activator.CreateInstance(constructed);

(X signifies it's the same as the corresponding variable without the X).

This topic is closed to new replies.

Advertisement