What does StreamingContextStates.Clone actually do?
Asked Answered
S

1

8

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?

Shekinah answered 17/6, 2013 at 20:24 Comment(3)
For the record, I strongly suggest that you avoid BinaryFormatter in, well, most circumstances. It has some things where it is handy, but I've seen so many people have so much pain caused from this... indeed, the issues in BinaryFormatter were part of why I got heavily involved in serialization a few years backSnatch
This property is re-exposed in ISerializable.GetObjectData(...), so technically any implementation could in theory choose to do something different based on the StreamingContextStates value. I don't know how many, if any, do, thoughSnatch
@MarcGravell Interesting, thanks. (And perhaps that sample should be taken out of CLR Via C# for the next edition then. ;)Shekinah
B
2

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!)

Bendicty answered 4/7, 2013 at 16:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.