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:

public partial class SomeClass
    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:

public partial class SomeClass
    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.

Posted 02-09-2010 1:31 PM by Scott Seely


About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)