Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does StreamingContextStates.Clone actually do?

The book CLR Via C# presents a simple way to clone objects via binary serialization.

It specifies StreamingContextStates.Clone when creating the BinaryFormatter like so:

var formatter = new BinaryFormatter
{
    Context = new StreamingContext(StreamingContextStates.Clone)
};

The documentation for StreamingContextStates.Clone says that it

Specifies that the object graph is being cloned. Users can assume that the cloned graph will continue to exist within the same process and be safe to access handles or other references to unmanaged resources.

Well fair enough - but I don't really know what this actually means. In what way does this actually change the behaviour of the BinaryFormatter? Can anyone list any concrete effects that using this flag has?

like image 306
Matthew Watson Avatar asked Jun 17 '13 20:06

Matthew Watson


1 Answers

Serialization is the subject here.
MS provided an "abstract" mini-framework to allow serialization of objects.
Binary formatter is a specific implementation of that mini-framework concepts.

A developer may choose to use that framework concepts to create his own custom formatter - or -
MS itself when creating the mini-framework thought of further implementation of serialization.

So they provided those flags as part of the framework.

To answer your specific question: those flags will not have any effect to binary formatter as it is already implemented as a tool (if you like) to track the object graph and simply convert it into bytes of raw data.
If you create your own serializer which in example can save the object to a database or to a file or to shared memory or whatever - you would want the user who using your serializer to specify the corresponding flag.

Unless I totally misunderstood MS devs since 2003 .. :) (which is possible!)

like image 75
G.Y Avatar answered Sep 30 '22 08:09

G.Y