Sign in to follow this  

[.net] Serializing generic classes

Recommended Posts

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!

Share this post

Link to post
Share on other sites
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 :-)

Share this post

Link to post
Share on other sites
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

Share this post

Link to post
Share on other sites
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).

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this