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.