zimopisec
zimopisec

Reputation: 1

Serialization of child class from function of parent

I have a number of objects that i want to serialize and read to object's instance later. But, if i try to write a Save function like this:

[serializable]
public class ClassA
{
  public int a;
  public string b;
  ...
  public String Save()
  {
  return XmlSerialized.Serialize(this);
  }
}

[serializable]
Class ClassB: ClassA
{
   ****
  bool C;
}

The following code returns only objects of class A:

ClassA objA = new ClassB();
string s = objA.Save();

How can i solve this problem?

Upvotes: 0

Views: 539

Answers (3)

eladcon
eladcon

Reputation: 5825

First thing, you need to make bool C public in order to serialize it. Next, initiate a new XmlSerializer with the type of this, and use it to serialize:

    public string Save()
    {
        XmlSerializer serializer = new XmlSerializer(this.GetType());

        using(StringWriter writer = new StringWriter())
        {
           serializer.Serialize(writer, this);
           return writer.ToString();
        }
    }

Then you can call it like you first did:

ClassA objA = new ClassB();
string s = objA.Save();

Upvotes: 1

Jevgeni Geurtsen
Jevgeni Geurtsen

Reputation: 3133

Using ClassA objA = new ClassB(); wouldn't work. .NET will see the result type is ClassA and it knows that ClassB inherits from ClassA. Thus it will just create an instance of ClassA.

Upvotes: 1

H W
H W

Reputation: 2586

You call the Save method of classA which is why this is an instance of class A. By using

ClassB objB = new ClassB(); 
string s = objB.Save();

you should get the desired result.

(Though i am not quite sure if you need an overload of Save() in ClassB.)

Upvotes: 0

Related Questions