views:

66

answers:

1

I'm learning about serialization in C# and I have the basics down, but now I am trying something a little more complicated and I'm looking for some pointers on best practice (I can achieve what I want, I just want to know the 'right'/easiest/least code/most robust method of doing it).

I have a racing track which is made up of sections. Each section type inherits from a common TrackSection class. The TrackSection class holds a lot of data on geometry and other things that I don't want to save out and it needs some context information when the constructor is called, so I have implemented the ISerializable interface and provided my own methods to handle (de)serialization. The classes that inherit from TrackSection are a lot simpler, and I would be happy for all their fields to be serialized automatically, but I assume that since the base class is ISerializable they probably need to do it manually as well (I have added the deserialization constructor and call the base class's deserialization constructor in each). When it comes to serializing though I'm not sure what to do, I would have expected ISerializable's GetObjectData() method to be virtual so I could extend the serialization in sub-classes. Do I simply need to implement my own virtual method that is called from the base class's GetObjectData(), or am I going about this all wrong?

As I say, I have it working but any better solution or any general tips about what I'm doing would be much appreciated, as I can't help but feel my solution is a little more complicated than it needs to be. Thanks.

+1  A: 

Unless you're doing something where you need to implement ISerializable, you could, instead just mark the class with the Serializable attribute and mark the fields that you don't want serialized as NonSerialized

SnOrfus
I had considered that, but my constructor requires some context information and I wasn't sure how to do that without the custom methods (other than maybe a static class that stores the context information, but that wouldn't be thread safe).
Byker Dave