DataContract, Partial Types and Generated Code


The other day, a friend had an issue with a DataContract. He had an Entity Model that used DataContract serialization. The code, stripped down to its essence, had something like this:

[DataContract]
public partial class SomeClass
{
    [DataMember]
    public int MyInt { get; set; }
}

 

And this was all well and good. When transmitting SomeClass over the wire, the fields on the entity model were transmitted. Now, my friend is really smart, and he knew that his version of serialization had implicit serialization. So, when adding new fields, he relied on implicit field serialization by augmenting SomeClass in a separate file as:

public partial class SomeClass
{
    public string MyString { get; set; }
}

 

Lo and behold, the field MyString didn’t appear on the wire. Why was this? This is because partial classes are a compiler trick that hides itself at the assembly level. The assembly indicated that SomeClass is a type that has the following C# implementation:

[DataContract]
public partial class SomeClass
{
    [DataMember]
    public int MyInt { get; set; }

    public string MyString { get; set; }
}
 

This shows that MyString is not part of the data contract, so the field doesn’t get serialized. At the assembly level, no one knows that you separated the implementation across two files.

So, next time you are wondering why part of your object isn’t being serialized, see if you made any declarations about serialization on the type. If you did, you have turned off the automatic “magic” parts of serialization. Sometimes, wizards will make those decisions for you. One way to recognize that the work was done for you: look to see if the generated type has [DataContract] on the partial class you are augmenting.

<span>%d</span> bloggers like this: