One of the new WCF features in .NET 3.5 SP1 is that DataContractSerializer now supports serializing types that aren’t annotated with any serialization attributes like [DataContract] or [Serializable]. If you were using DataContractSerializer prior to SP1, you had to follow the rules outline by Sowmy here . These rules illustrate that for custom classes you have a few choices. You can annotate the class with [DataContract] and [DataMember] to define an attribute-based mapping or implement IXmlSerializable to define a custom mapping. Or you can annotate the class with [Serializable] to automatically map all fields (like with .NET Remoting) or implement ISerializabe to take things into your own hands (assuming IXmlSerializable wasn't used). As you can see from the rules , there is no allowance for types that haven’t been annotated with one of these serialization attributes or that implement one of the serialization-related interfaces, or in other words, you can't serialize “plain old C# objects“ ( POCO for short). The support for [Serializable] provided a nice migration path for traditional .NET Remoting types, which was nice, but the lack of support for POCO types meant you couldn’t move your ASP.NET Web services (ASMX) types over to the DataContractSerializer without sprinkling a bunch of new attributes on them. Now, with .NET 3.5 SP1, you can serialize the following type with DataContractSerializer: public class Person { public Person() { this .Id = Guid .NewGuid().ToString(); } private string Id; public string Name; public Person Spouse; } For POCO types, DataContractSerializer only includes the public read/write fields and properties into the resulting XML Infoset. So in our example above, the private Id field won’t make it into the message. Now you can simply use POCO types in your WCF service contracts and you don’t have to worry about changing the serializer back to XmlSerializer using [XmlSerializerFormat]. In other words, the following service contract works with the above type as-is in .NET 3.5 SP1: [ ServiceContract ] public interface IMarriageService { [ OperationContract ] void MarryPeople( Person p1, Person p2); } Here’s a simple console program that uses DataContractSerializer to serialize a Person object: class Program { static void Main( string [] args) { Person p = new Person (); p.Name = "Aaron" ; p.Spouse = new Person (); p.Spouse.Name = "Monica" ; DataContractSerializer dcs = new DataContractSerializer
Read More...