Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to flush and set the stream position to 0 in this serialization snippet?

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.

like image 892
vexe Avatar asked Oct 17 '25 07:10

vexe


1 Answers

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.

like image 131
ChaseMedallion Avatar answered Oct 19 '25 20:10

ChaseMedallion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!