Explicit private backing fields are completely unnecessary for XmlSerializer
, which can only serialize public fields and properties. As long as the backing field is private, XmlSerializer
has no way of detecting whether it is explicit or secretly created by the compiler as described in the docs:
When you declare [an auto-implemented property], the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
If you are only serializing using XmlSerializer
(or json.net with DefaultContractResolver.IgnoreSerializableAttribute = true
, which is the default), go right ahead and simplify your classes by using auto-implemented properties.
However, do be aware that auto-implemented properties work poorly with [Serializable]
. When you mark a type with this attribute, you are indicating that it can be serialized by serializing its internal state -- its public and private fields1 -- rather than its external state -- its public properties. While this attribute is completely ignored by XmlSerializer
, certain other serializers support it, including DataContractSerializer
, DataContractJsonSerializer
and BinaryFormatter
. If you add the attribute to a type with auto-implemented properties, the names of the secret "anonymous" backing fields can start to appear in serialization streams created by those serializers. This sometimes leads to problems such as those in the following questions:
So, if you are using auto-implemented properties, my recommendation would be to remove the [Serializable]
attribute from your type. You probably don't need it, data contract serialization works better without it, and in any event its use is being deprecated in .NET Core, as shown here and here. (Though reportedly binary serialization is getting implemented to some extent in .NET Core 2.0, see here for details.)
1 Why fields? In the .Net 1.1 time frame, there were still debates about whether serializing private state might be preferable to serializing public state. This is no longer debated, serialization of public state (or of state as specified by some data contract) is preferred.