views:

57

answers:

2

Suppose I have an application with the following code:

public class Node
{
  public Node Clone() {//implementation}

  public List<Node> Children{get;set;}

  //Many properties
  public string Content { get; set; }
  // ... etc ...
}

I use serialization in two different scenarios:

  1. Saving my objects to the disk, and
  2. Performing deep cloning.

When I want to serialize the objects to the disk, I would like the Children to be serialized as well.

However, when I use serialization to perform deep cloning, I do not want the children to be serialized. I am going over the children in a loop and call every child's Clone method, and then add it to the parent.

I would like to know if it is possible to control the serialization, so that I'll be able to tell the Serializer whether to serialize specific field or not.

In case it is not possible directly, I am using binary serialization for deep cloning and XMLSerialization for saving my objects. Maybe that could help somehow.

+2  A: 

You can make your class implement IXmlSerializable to provide complete control of the serialization when you're using the XmlSerializer, and ISerializable to control serialization in other cases.

Reed Copsey
+4  A: 

So you want the deep (BinaryFormatter) version to skip the list?

public List<Node> Children{get;set;}

to

[NonSerialized]
private List<Node> children;
public List<Node> Children {
    get {return children;}
    set {children = value;}
}

XmlSerializer doesn't look at [NonSerialized] - it just looks at the public members (Children) - so it should still serialize them.

Marc Gravell