Serialization of an Inherited Class.!

R

R Karthick

I am new to serialization. Apologies, if my question sounds really
basic. Stuck in this problem for the last two hours. Thought, will ask
the experts instead of banging my head more.

This is what I have..!

<code>

Abstract Class FooBase
{

}

Abstract Class FoobaseCollection : ICollection, IEnumerable
{
private ArrayItem fooBaseList;

public foobase this[int index]
{
get
{
...
...
}
}

public void Add(FooBase object)
{
....
}
}

[XmlRoot("Foobar")]
Class Foobar : Foobase
{

}

[XmlRoot("FoobarCollection")]
Class FoobarCollection : FoobaseCollection
{

}


</code>

When I serialize the object using

<code>

FoobarCollection foobarCollection = new FoobarCollection();
foobarCollection.Add(new FooBase());
XmlSerializer serializer = new
XmlSerializer(typeof(FoobarCollection), new Type[] {typeof(Foobar)});
XmlTextWriter xmlTextWriter = new XmlTextWriter(@"C:\foobar.xml",
System.Text.Encoding.Default);
serializer.Serialize(xmlTextWriter, foobarCollection);
</code>

I dont get the expected xml. The internal arraylist elements are
serialized into tags with base class types(FooBase) rather than its
own type(FooBar).

eg:

<xml>

<FoobarCollection>
<FooBase ... />
<FooBase ... />
<FooBase ... />
</FoobarCollection>

instead of

<FoobarCollection>
<Foobar... />
<Foobar ... />
<Foobar ... />
</FoobarCollection>

</xml>


Am I missing something here. I cannot add the XmlElement or
XmlArrayList attribute to the base class property(public foobase
this[int index]), as I dont want to hardcode the type into some
inherited class name.

Is this a limitation in the pattern I have implemented?

Thanks!
-Karthick R
 
J

Jon Skeet [C# MVP]

R Karthick said:
I am new to serialization. Apologies, if my question sounds really
basic. Stuck in this problem for the last two hours. Thought, will ask
the experts instead of banging my head more.

When I serialize the object using

<code>

FoobarCollection foobarCollection = new FoobarCollection();
foobarCollection.Add(new FooBase());
XmlSerializer serializer = new
XmlSerializer(typeof(FoobarCollection), new Type[] {typeof(Foobar)});
XmlTextWriter xmlTextWriter = new XmlTextWriter(@"C:\foobar.xml",
System.Text.Encoding.Default);
serializer.Serialize(xmlTextWriter, foobarCollection);
</code>

Um, that's adding a new FooBase, not a Foobar - in other words, it
shouldn't be trying to serialize it as a FooBar. However, it's hard to
know whether that's just a bug in your sample code or not.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top