I have a base class and another derived from it. Let's assume, the base class has 20 members and derived has 5 members. Only the derived class is serializable.
After I instantiate, the derived class's object has all 25 members. Now how can I only serialize the 5 members of derived class? When I use "this" to serizalize or deserialize, the entire class (all 25 members) is serialized and then deserialized.
Here is a code snippet (not complete):
// Base class definition.
public abstract class baseMyClass
{
// declaration of members
}
...
// Derived class definition.
[Serializable]
public sealed class MyDerivedClass : baseMyClass
{
// declaration of members
}
...
// Serializing the object.
StringWriter writer = new StringWriter();
XmlSerializer xs = new XmlSerializer(typeof(MyDerivedClass));
xs.Serialize(writer, this);
...
// Deserializing the object.
StringReader reader = new StringReader(System.Text.Encoding.UTF8.GetString(data));
XmlSerializer xs = new XmlSerializer(typeof(MyDerivedClass));
MyDerivedClass objMyDerivedClass = (MyDerivedClass)(xs.Deserialize(reader));
I couldn't find any similar example. If you know one, please point me to it.
Thanks for all the help.
Instead of inheriting, I made the class (which can be serialized) a member of the parent class. The parent class is not a parent anymore. I will just instantiate objects of this class and it will have a member object which can be serialized.
Use the [NonSerializedAttribute] attribute on every field you don't want to serialize.
Or implement the ISerializsable interface and manually serialize the fields you need on the derived class.
http://msdn.microsoft.com/en-US/library/axwwbcs6(v=vs.80)
http://msdn.microsoft.com/en-us/library/ty01x675(v=vs.80).aspx