views:

228

answers:

1

I have create testing application that has 3 classes

  • Car
  • Radio
  • SportCar : Car (has a Radio)

As the serialize process when I create instance of XmlSerializer object I use 2 object to testing

XmlSerializer xmlSerializer = new XmlSerializer(typeof(SportCar));

and

XmlSerializer xmlSerializer = new XmlSerializer(
    typeof(SportCar), 
    new Type[] { typeof(Car), typeof(Radio) });

The result of this 2 approach is identical, so I want to know what is the difference between these 2 constructor or critical point that need to use #2 constructor?

+8  A: 

The big difference is when you need to tell XmlSerializer about sub classes - for example:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Car),
     new Type[] { typeof(SportCar), typeof(Radio) });

Here, without the extra info if wouldn't have known (just from Car) about either SportCar or Radio - so if you give it a object that is actually a SportCar, it would fail:

Car car = new SportCar {...};
xmlSerializer.Serialize(destination, car);

You can also do this by setting [XmlInclude(typeof(SportCar))] against the Car type definition:

[XmlInclude(typeof(SportCar))]
public class Car {...}

This is easier, but is only possible if the Car type is in an assembly that knows about SportCar. But you often do know this, so XmlInclude is the preferred option.

Additionally: there are some efficiency benefits of XmlInclude; behind the scenes the system uses dynamic type generation to make XmlSerializer efficient. For this reason, you should generally keep hold of (and re-use) the XmlSerializer instance you create; for example, by storing it in a static field. However, the system does this automatically for the default usage (new XmlSerializer(typeof(Car))) - i.e. no matter how many times you use this constructor, it only generates the dynamic code once. If you use the more complex constructor (new XmlSerializer(typeof(Car),new Type[] { typeof(SportCar), typeof(Radio) })) it will do the type generation each time.

Marc Gravell
What is the difference in the output if I specify the sub class info? (I'm new to Serialize process)
In The Pink
There is no difference in output between using the XmlInclude approach and the constructor (new Type[]) approach; they are equivalent. If you do neither, and ask for a XmlSerializer(typeof(Car)), but give it a SportCar - it will throw an exception.
Marc Gravell
I see, after reading topic about XmlSerializer on C# 3.0 in a nutshell and back to read your answer that mention about "about sub classes" it make me understand how XmlSerializer work. (I purchase another book to study on C#, too bad.)
In The Pink