Question

I've been trying to understand how to correctly implement a circular reference using the ISerializable interface. But i have not been able to work out even in a simple form, I have read the explanation here

But I have not been able to implement it, I've also tried looked for an example to no avail. I've checked the documentation on MSDN, but i unable to any reference to how to handle custom serialization with circular references.

The simplest form i've been trying with is a doublely linked list.

Was it helpful?

Solution

Serialize circular reference just need an strategy to serialize the whole object graph nothing more. for double link list you can start from the first node and then just serialize the next one, (previous is already serialized so nothing to do ) then when you wanted to build the list again do the same just set previous node for each one sequentially(recursively) something like this

public class LinkList : ISerializable
{
    public Node First { get; set; }

    public Node Tail { get; set; }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Firts", First);
    }
    public LinkList(SerializationInfo info, StreamingContext context)
    {
        First = info.GetValue("First", typeof(Node)) as Node;
        First.PrevNode = null;
        //do one one while set the Tail of this class  and LinkList proeprty for each node
    }
}
public class Node : ISerializable
{
    public LinkList LinkList { get; set; }


    public Node(SerializationInfo info, StreamingContext context)
    {
        Name = info.GetString("Name");
        NextNode = info.GetValue("NextNode", typeof(Node)) as Node;
        if(NextNode != null)
            NextNode.PrevNode = this;

    }
  public  Node PrevNode
    {
        get;
        set;
    }
    public Node NextNode
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", Name);
        info.AddValue("Next", NextNode);

    }
}

OTHER TIPS

One option to get this to work would to be to add an ID field to the the class. Make a linked list of integers which will tie to the ID of the field, and a readonly linked list property which will be populated based on finding references to the IDs in the linked list.

The one constraint on this is that each object in the list of IDs must be available when it is deserialized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top