Datatypes for MemoryStream.Capacity vs MemoryStream.Length

.net, c#, memorystream

Solution

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.

Problem

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?

Original source

Related problems