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?
The big difference is when you need to tell
XmlSerializerabout sub classes – for example:Here, without the extra info if wouldn’t have known (just from
Car) about eitherSportCarorRadio– so if you give it a object that is actually aSportCar, it would fail:You can also do this by setting
[XmlInclude(typeof(SportCar))]against theCartype definition:This is easier, but is only possible if the
Cartype is in an assembly that knows aboutSportCar. But you often do know this, soXmlIncludeis the preferred option.Additionally: there are some efficiency benefits of
XmlInclude; behind the scenes the system uses dynamic type generation to makeXmlSerializerefficient. For this reason, you should generally keep hold of (and re-use) theXmlSerializerinstance 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.