Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatypes for MemoryStream.Capacity vs MemoryStream.Length

Today I noticed something strange with the MemoryStream class. The .Length property is a long, but the .Capacity property, which should presumably always be >= .Length is only an int.

I know that it would take a stream of over a GB to for Length to exceed possible Capacity, but this seems very strange to me. Length can't be changed, because it's inherited from Stream, but why not make Capacity a long as well? What happens to the capacity if you do have a MemoryStream that exceeds int.MaxValue in length?

like image 894
Bobson Avatar asked Nov 24 '14 19:11

Bobson


People also ask

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.

What is use of MemoryStream in C#?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.


3 Answers

No, MemoryStream.Capacity can't exceed the int.MaxValue because memory stream is backed by a byte[] and arrays maximum length is int.MaxValue.

However, Stream.Length is long, that makes sense because stream can be anything, For example FileStream.Length can be greater than int.MaxValue undoubtedly.

like image 140
Sriram Sakthivel Avatar answered Sep 18 '22 17:09

Sriram Sakthivel


A fundamental limitation in .NET, unfortunately, is that objects cannot exceed 2GB in size. The Stream class needs the long for its Length property, because a Stream can represent a resource outside of .NET (e.g. a file), but since MemoryStream is known to always be an in-memory, managed object, it is guaranteed to always be able to fit its Capacity in an int.

like image 28
Peter Duniho Avatar answered Sep 19 '22 17:09

Peter Duniho


The Length property is inherited from Stream, while the Capacity property is declared for MemoryStream. Streams in general may be larger than 2GB, but this particular kind of stream never will be -- hence, the Capacity that is specific to MemoryStream is just an int.

like image 29
danwyand Avatar answered Sep 17 '22 17:09

danwyand