I’m serializing an object to a byte[] using MemoryStream:
byte[] serialized = new byte[1000];
using (MemoryStream stream = new MemoryStream(serialized))
using (TextWriter textWriter = new StreamWriter(stream))
serializer.Serialize(textWriter, stuffToSerialize);
is there any way I can set 'serialized' to grow according to the size of the stuffToSerialize?
The parameterless constructor
new MemoryStream()uses one.Then serialise into it, and then when you need the
byte[]callToArray()which creates a copy of whatever length of the buffer was actually used (the internal buffer will generally have some growing space at any point, and that’s normally not desirable,ToArray()gives you what you actually care about).At the end of the following code, it will have the same effect as your code, were you able to predict the correct size: