Well, in the first case, the written XML looks something like this:
<Barn> <Horse> <Rider xsi:nil="true" xmlns="abc" /> </Horse> </Barn>
However, in the second case, the XML looks like this:
<Barn> <Horse /> </Barn>
Thus, in the second case, what is essential during deserialization is the following:
Barn barn = new Barn(); barn.Hose = new Horse();
So, since we set the default Rider in the constructor, it remains as "Jim Craig."
Interestingly, the behavior can be changed simply by changing the order of the elements in Barn . To try to find more, we can do some digging using ILSpy and Sgen.exe - just run sgen against our assembly and look into the generated assembly.
We found that in the first case, the generated code in and the Write2_Horse and Write3_Motorcycle have a line that looks like this:
base.WriteNullableStringLiteral("Rider", "abc", o.Rider);
However, in the second case, it looks like this:
base.WriteElementString("Rider", "abc", o.Rider);
I see no reason why changing the order of such elements should change the serialization behavior of both Horse and Motorcycle elements in such a way, so, in short, this seems like an error to me in the XML serialization assembly generator.
You should probably report this to Microsoft :-)