Serializing a class

Does anyone have any pointers on how to generically serialize a class.

Is there anyway to deserialize data into a class without knowing which class it is?

I am developing a game for which I would like to store the state of various game objects for later playback. Each of the classes of game objects have different properties that are important to be recorded. (position, or enabled state, or rotation, or any number of properties or combinations of them.)

I have a “GameRecorder” object which I plan to have methods to start/stop the recording, load/save the recording, and accumulate the various gameobject updates. It reads from an array set in the editor of my GameManager which objects should be recorded.

This was fairly easy when the state I was recording was all the same type of data. For example, if I needed to know position and enabled or not for each object I made up a class that encapsulated that and made a collection of that type for which I added updates to. When it came to write this information to file or read it back the format was fixed and BinaryWriter/BinaryReader worked fine along with getting or setting values directly into the class members.

I’d like however to make the RecorderObject agnostic as to what type of data it is receiving or restoring. The only way I can think of how to do this is very un-object oriented. The updates it would receive are not the same and I cannot just make a collection of disparate objects.

Make a class that has a Dictionary for every type of base data type you use. For example: Dictionary<string,int>, Dictionary<string,float>, Dictionary<string,bool>, etc. For any class you need to serialize, create a Serialize method that instantiates an instance of this Dictionary class and loads the value of each variable into the appropriate Dictionary with a string key, such as the variable name, or better yet the classname.variablename. Different objects of different classes could even access the same Dictionary object and add/read their data. Just make sure each object uses a unique string key to store their data.

Thanks for the idea.