Search code examples
c#encapsulationdatacontractdata-members

C# model encapsulation with serializable


I am using serializable, but cannot leave my private class.

[DataContract]
public class test
{
    [DataMember]
    public String name { get; set; }
}

what problems in leave this class in public.

I do not understand this encapsulation, because I can't use it this way.

[DataContract]
public class test
{
    [DataMember]
    private int myVar;

    public int MyProperty
    {
        get { return myVar; }
        set { myVar = value; }
    }
}

Solution

  • A data contract is something public. A contract between two parties. The other party may not even have the same internal representation as you have. It will work as long as the public contract is fulfilled.

    If you want to serialize the object yourself, you can use other ways, for example implementing IXmlSerializable for XmlSerialization.