Information Technology Reference
In-Depth Information
graphs: Even if you have circular references in your objects, the serialize
and deserialize methods will save and restore each actual object only once.
The .NET Serialization Framework also will re-create the web of refer-
ences when the web of objects is deserialized. Any web of related objects
that you have created is restored correctly when the object graph is dese-
rialized. A last important note is that the Serializable attribute supports
both binary and SOAP serialization. All the techniques in this item will
support both serialization formats. But remember that this works only if
all the types in an object graph support serialization. That's why it's
important to support serialization in all your types. As soon as you leave
out one class, you create a hole in the object graph that makes it harder for
anyone using your types to support serialization easily. Before long, every-
one is writing their own serialization code again.
Adding the Serializable attribute is the simplest technique to support seri-
alizable objects. But the simplest solution is not always the right solution.
Sometimes, you do not want to serialize all the members of an object:
Some members might exist only to cache the result of a lengthy operation.
Other members might hold on to runtime resources that are needed only
for in-memory operations. You can manage these possibilities using attri-
butes as well. Attach the [NonSerialized] attribute to any of the data mem-
bers that should not be saved as part of the object state. This marks them
as nonserializable attributes:
[ Serializable ]
public class MyType
{
private string label;
[ NonSerialized ]
private int cachedValue;
private OtherClass otherThing;
}
Nonserialized members add a little more work for you, the class designer.
The serialization APIs do not initialize nonserialized members for you dur-
ing the deserialization process. None of your types' constructors is called,
so the member initializers are not executed, either. When you use the seri-
alizable attributes, nonserialized members get the default system-initialized
value: 0 or null. When the default 0 initialization is not right, you need to
 
Search WWH ::




Custom Search