Data Types for MemoryStream.Capacity and MemoryStream.Length

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

I know that a stream will require a stream of more than GB so that the length exceeds the possible bandwidth, but it seems very strange to me. Length cannot be changed since it is inherited from Stream , but why not make Capacity a long ? What happens to capacity if you have a MemoryStream that is longer than int.MaxValue ?

+5
source share
3 answers

No, MemoryStream.Capacity cannot exceed int.MaxValue , because the memory stream is supported byte[] and the maximum length of the int.MaxValue array .

However, Stream.Length is long , it makes sense because the stream can be anything, for example FileStream.Length can be larger than int.MaxValue , no doubt.

+7
source

The main limitation in .NET, unfortunately, is that objects cannot exceed 2 GB. The Stream class needs a long for its Length property, because Stream can represent a resource outside of .NET (for example, a file), but since a MemoryStream , as you know, is always internal memory, a managed object, it will always be able to set its Capacity to int .

+3
source

The Length property is inherited from Stream , and the Capacity property is declared for MemoryStream . Streams in general can be more than 2 GB, but this particular type of stream will never be - therefore, the Capacity characteristic of a MemoryStream is just int .

+2
source

Source: https://habr.com/ru/post/1207613/


All Articles