WCF Serialization Basics - Opt In

20 April 2010

This post is part of a series of posts that I am writing as I prepare for a presentation on WCF basics. Prior to WCF, when exposing a web service, serialization was done using the SoapFormatter class. Using the SoapFormatter, the developer would tag the class being serialized with the Serializable attribute, and the SoapFormatter would serialize all of the fields in the class, regardless of visibility, unless you opted out by assigning the NonSerialized attribute to a field that you wanted to excluded.

 1 //Add reference to:
 2 //System.Runtime.Serialization.Formatters.Soap.dll
 3 
 4 using System;
 5 using System.IO;
 6 using System.Text;
 7 using System.Collections.Generic;
 8 using System.Runtime.Serialization;
 9 using System.Runtime.Serialization.Formatters.Soap;
10 
11 [Serializable]
12 public class Person
13 {
14   //Note: Cannot assign this to a property.
15   //Must use field back property
16   [NonSerializedAttribute]
17   private string _lastname;
18 
19   public int ID {get;set;}
20 
21   public string FirstName {get;set;}
22   public string LastName
23   {
24     get {return _lastname;}
25     set {_lastname = value;}
26   }
27 }
28 
29 public class TestApp
30 {
31   public static void Main()
32   {
33     try
34     {
35       var person = new Person();
36       person.ID = 1;
37       person.FirstName = "Fred";
38       person.LastName = "Flintstone";
39 
40 
41       using(var memStrm = new MemoryStream())
42       {
43         IFormatter formatter =
44         new SoapFormatter();
45         formatter.Serialize(memStrm, person);
46 
47         var data = new byte[memStrm.Length];
48         Array.Copy(memStrm.GetBuffer(),
49         data, data.Length);
50         var text =
51         Encoding.UTF8.GetString(data);
52         Console.WriteLine(text);
53       }
54     }
55     catch (Exception e)
56     {
57       Console.WriteLine(e.ToString());
58     }
59     finally
60     {
61       Console.Write("Press any key...");
62       Console.ReadKey();
63     }
64   }
65 }

As you can see in the output above, the _lastname field was not serialized by the SoapFormatter because it was tagged with the NonSerialized attribute.

One of the problems with the SoapFormatter's opt-out approach is that every time you add a field to a class that is serializable, you have to consider whether or not the new field is serializable. If it is not, you will not get an error until run-time. The developer also has to remember that when the a new auto-implemented property is added to a class, the compiler adds fields to the class behind the scenes. This is true for both the "ID" and "FirstName" properties in the example above as is evident in the long, awkward xml node names that end with "BackingField."

To get around this, WFC's DataContractSerializer follows an opt-in approach. With the DataContractSerializer, the developer tags the class being serialized with the DataContract attribute, and then tags the fields and/or attributes that should be serialized with the DataMember attribute. Only the fields and/or properties that were tagged with the DataMember attribute will be included in the serialized stream.

 1 //Add reference to System.Runtime.Serialization.dll
 2 
 3 using System;
 4 using System.IO;
 5 using System.Text;
 6 using System.Collections.Generic;
 7 using System.Runtime.Serialization;
 8 using System.Runtime.Serialization.Formatters.Soap;
 9 
10 [DataContract]
11 public class Person
12 {
13   //demonstrates serialization of a field
14   [DataMember]
15   private string _firstName;
16 
17   //demonstrates serialization of a property
18   [DataMember]
19   public int ID {get;set;}
20 
21   public string FirstName
22   {
23     get {return _firstName;}   
24     set {_firstName = value;}
25   }
26 
27   //demonstrates data that was not serialized
28   public string LastName {get;set;}
29 }
30 
31 public class TestApp
32 {
33   public static void Main()
34   {
35     try
36     {
37       var person = new Person();
38       person.ID = 1;
39       person.FirstName = "Fred";
40       person.LastName = "Flintstone";
41 
42       using(var memStrm = new MemoryStream())
43       {
44         var pType = person.GetType();
45         var serializer = new DataContractSerializer(pType);
46         serializer.WriteObject(memStrm, person);
47 
48         var data = new byte[memStrm.Length];
49         Array.Copy(memStrm.GetBuffer(), data, data.Length);
50         var text = Encoding.UTF8.GetString(data);
51         Console.WriteLine(text);
52       }
53     }
54     catch (Exception e)
55     {
56       Console.WriteLine(e.ToString());
57     }
58     finally
59     {
60       Console.Write("Press any key...");
61       Console.ReadKey();
62     }
63   }
64 }

As you can see in the above example, the LastName property was not serialized because it did not have the DataMember attribute. Also notice that the "ID" property was serialized at the property level, but the first name was serialized at the field name.

WCF added the flexibility to serialize not only at the field level, but also at the property level. This flexibility adds a lot of power, but it can also lead to unexpected results. Be careful not to add the DataMember attribute to both the property and its backing field. In this situation, both will be serialized. Not only does this clutter your data contract and add unnecessary traffic over the wire, but it also can lead to weird behavior or an error.

WCF's opt-in approach also helps immensely in practice because it complies with the third tenet of Service Oriented Architecture that states "Services share schema and contract, not class." When you chose to add the DataMember attribute to a member of a DataContract class, you are choosing to change the contract. This was not the case when you decided to add a private field to a class marked Serializable.