Question

Taken from here:

    private static string SerializeToString<T>(T value)
    {
        using (var stream = new MemoryStream()) {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, value);
            stream.Flush();
            stream.Position = 0;
            return Convert.ToBase64String(stream.ToArray());
        }
    }

    private static T DeserializeFromString<T>(string data)
    {
        byte[] b = Convert.FromBase64String(data);
        using (var stream = new MemoryStream(b)) {
            var formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }

Why do I need to flush and set the position to 0 in the serialize method, and seek in the deserialize method?

I removed them, they didn't affect anything.

I know that flushing means write whatever that's in the stream immediately.

But I don't know if it's necessary here... also not sure about the position and seek.

Was it helpful?

Solution

These samples contain unecessary code. The documentation for MemoryStream.ToArray (here) explicitly states that:

Writes the stream contents to a byte array, regardless of the Position property.

Thus, we clearly don't need to set position. The flush is more debatable. It's very, very unlikely that memory stream would buffer under the hood, since it's just writing to a memory buffer anyway. However, I'm not sure that it's documented anywhere that memory stream won't buffer, so Flush() might be reasonable since we're calling ToArray() before disposing the stream. Another approach would be to call ToArray() outside the using block (we'd have to move the declaration of the variable out as well). This will work because ToArray() states that:

This method works when the MemoryStream is closed.

On the read side, you are creating a new stream, which starts at position 0 by default. Thus, there's no need for the Seek call.

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