Search code examples
c#datacontract

C# DataContract Attribute for Private Fields?


For a class marked with the attribute, [DataContract], does its private fields, which should be serialized, be marked as [DataMember]?

Example:

[DataContract]
public class Component
{

// [DataMember] is not needed since public fields get automatically serialized
public int number;

// do I need [DataMember] here?
private string characters;

// [DataMember] is required here, but I also need to include the 
// attribute [DataMember] in this class's definition
private complexType cT;

I'm reading DataContractAttribute Class correctly, right?


Solution

  • No, it doesn't look like you are reading the documentation correctly.

    DataContracts are a way to publicly share information that is a little different than regular serialization.

    From the documentation page you link:

    The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized.

    But that only applies if you add the [DataContract] attribute like you did.