This is probably a really simple question, I think all that I am after is Best Practice for declaring a new MemoryStream
What is the difference between the following 2 samples:
MemoryStream myStream = new MemoryStream(0x10000);
or
MemoryStream myStream = new MemoryStream();
Obviously, I know that the first example set the initial capacity of the stream. But, both of these have an automatically resizable capacity.
I there any reason why I should use one method as opposed to the other?
You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.
MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.
From expirience I can say, that it does not copy the array. Be aware though, that you are unable to resize the memory stream, when using an array in the constructor.
MemoryStream in C# programs allows you to use in-memory byte arrays or other data as though they are streams. Instead of storing data in files, you can store data in-memory.
There is overhead associated with re-sizing a memory stream. If you know or otherwise have a reasonable guess as to the expected size needed to be stored in the memory stream, you'll want to use that size as the initial capacity. Otherwise, the default size of 0 is used and will be resized as data is added.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With