I am trying to use the DataContractSerializer
to serialize a simple object:
public class MyType {
public string MyValue { get; set; }
}
I have done extensive research and discovered that according to MSDN, contrary to popular belief, the attribute [DataContract]
is optional, and if no attribute is specified on the class then all public read/write properties and fields are serialized. And indeed, when I serialize it so - it works as expected.
Now, if I add also a [Serializable]
attribute on the class, I get a different serialization that consists of the infamous prefix 'k__BackingField' (since my property is an auto property).
My questions:
- Can anyone explain why the DataContractSerializer would behave differently with and without the [Serializable] attribute? Not the technical explanation (which is probably something like "in this case the base class of XmlObjectSerializer is taking over"), but the design reason. I cannot see how this different serialization is useful in any way. If anything - it breaks backward compatibility. Does it make sense to suggest a change to Microsoft?
- If I don't want to go over our whole gigantic data model and decorate everything with [DataContract] and [DataMember] - is there a more generic way to tell the DataContractSerializer, or the WCF infrastructure (via a service contract attribute or such), to serialize also classes marked [Serializable] in its default (read: undecorated) behavior? Unfortunately, the attribute [XmlSerializerFormat] is not an option for me, I need to stick with the DataContractSerializer for WCF.