Jump to content
  • Advertisement
Sign in to follow this  

[.net] Serializing generic classes

This topic is 4232 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!