I have create testing application that has 3 classes
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With