Question

As discussed in Does the order of fields in C# matter?, the order of serializable properties affects, among other things, XmlSerializer output.

But if fields are in 2 files (using partial classes), does anyone know what in fact controls the resulting order? That is, which file's properties comes first?

(Background: I ask this because I've run into a scenario where one of the 2 files is auto-generated from xsd, and the other is manually edited. The test output is different on developer boxes vs. our scripted build box. Presumably this is a side effect of the several differences in the timing and history of the xsd->C# step in the 2 environments. Various ways to fix, but I'd like to understand the compilation process a little better if possible.)

Was it helpful?

Solution

Nothing is guaranteed per C# spec.

OTHER TIPS

I've found that using the 'easy' approach to making an object by marking it [Serializable] is usually only good enough for very simple implementations.

I would recommend that you implement the IXmlSerializable interface which is pretty easy to do and gives you all the control you need.

Here is what we found out through the fix of a nasty bug:

We had exactly the same problem, our serialization order has changed after a release without modifying any of the serialization related classes.

We had one half of a class generated from xsd-s, and the other half was hand-made. The order attributes were effect-less. What we saw was that before the release, the hand-made partial parts were serialized first, and after it the order changed.

The solution was in the order of the files in project file, that contained the two classes. It turned out, that after an MSBuild (on our build server) build, the serializer will put the elements of the earlier (in the csproj) ".cs" file first in the serialized XML. Changing the order of the ".cs" files in the csproj swapped the order and the generated parts were up front as needed in the XML.

This is is aligned with the answer and observation of Eric Hirst above, as renaming the file reorders the csproj's items (they are generally in alphabetical order). Watch out for editing the csproj by hand for this reason too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top