Data Contracts and Circular References

The DataContractSerializer is capable of serializing object trees that contain circular references. To enable this functionality you must mark the data contract with IsReference = true within the DataContractAttribute. The following sample code illustrates how to do this.

namespace CircularTest
{
  [DataContract(IsReference=true]
  public class Person
  {
    public Person(string firstName, string lastName, Person parent)
    {
      FirstName = firstName;
      LastName = lastName;
      Children = new List<Person>();
      Parent = parent;
    }

    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public List<Person> Children { get; set; }
    [DataMember]
    public Person Parent { get; set; } 
  }

  class Program
  {
    static void Main(string[] args)
    {
      Person kim= new Person("Kim", "Abercrombie", null);
      kim.Children.Add(new Person("Hazem", "Abolrous", kim));
      kim.Children.Add(new Person("Luka", "Abrus", kim));

      try
      {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Person));
        MemoryStream stream = new MemoryStream();
        dcs.WriteObject(stream, kim);
      }
      catch (Exception ex)
      {
        Console.WriteLine("An exception occured: " + ex.Message);
      }
    }
  }
}

See Also

Concepts

Serializable Types