Search code examples
c#.netdatacontractserializer

DataContractSerializer using default properties


Recently when I read the default behavior of DataContractSerializer, I get the rules from MSDN, however I do not understand the first rule which I extracted as below:

The DataContractSerializer infers a data contract from types without attributes using the default properties of the newly created types.

How do I interpret this statement, if some one has clear idea, could you help, I know that "without attributes", the attribute means DataContract attribute, however what does that "default properties" refer to. Is there something called "default properties" in a custom type?


Solution

  • If you a have type referenced within another class that has [DataContract] attribute, then DataContractSerializer will serialize the referenced type even if it is not attributed with [DataContract]. Serialization will happen on all public properties, unless the property is attributed with [IgnoreDataMember].

    For example:

    [DataContract]
    public class ClassA
    {
        public ClassB MyData { get; set; }
    
        public string SomeString { get; set; }
    
        public int SomeNumber { get; set; }
    
    }
    
    public class ClassB
    {
        public string SomeOtherInfo { get; set; }
    
        public int SomeOtherNumber { get; set; }
    }
    

    In the above code, ClassB will be serialized based on its default properties, which in this case are all the public properties: "SomeOtherInfo" and "SomeOtherNumber".