6

As I understand it you should use the Order property of the DataMember attribute so that you can add things to the data contract without the change in order causing things to break, but how should you approach this when you have base and sub types?

If I have datacontracts such as this:

[DataContract]
[KnownType(typeof(ChildDto))]
public class BaseDto
    {
    [DataMember (Name = "Property", Order = 0)]
    public string Property { get; set; }

    [DataMember (Name = "Property2", Order = 1)]
    public string Property2 { get; set; }
    }

[DataContract]
public class ChildDto:BaseDto
    {
    [DataMember (Name = "Property3", Order = 2)]
    public string Property3 { get; set; }

    [DataMember (Name = "Property4", Order = 3)]
    public string Property4 { get; set; }
    }

and I want to add a new data member property to BaseDto, what order should I give the property so that things don't break? Or should I not add anything to BaseDto? Can I add things to ChildDto?

Sam Holder
  • 32,535
  • 13
  • 101
  • 181
  • Curious to know, is the Order really needed? For what purpose are you or your service clients are using it? – thewpfguy Mar 19 '13 at 08:50
  • @thewpfguy the order is needed in case you update your contract in the future. By default the order will be alphabetical but you can specify the order to ensure that the new version of the contract can still be used by old clients which will ignore the new data if using the old contact. If the new data appears in the place previously used by some other data because of the changes then the old client either won't be able to use it or will use it incorrectly. – Sam Holder Mar 21 '13 at 18:27

1 Answers1

5

This is a breaking change. When adding new members to base classes WCF data contract serialization rules always serialize all members from the base class before any of the subclass' members.

You can read more about those rules in this MSDN page titled Data Member Order.

Drew Marsh
  • 33,111
  • 3
  • 82
  • 100
  • 1
    So that's it? You can never add a member to your base class if you are using data contracts? – Kim Aug 18 '15 at 08:05