开发者

why does "UInt64[] arr=new UInt64[UInt64.MaxValue];" throw exception?

开发者 https://www.devze.com 2022-12-24 00:41 出处:网络
开发者_StackOverflow社区Why does following code throw exception \"Arithmetic operation resulted in an overflow.\" ?
开发者_StackOverflow社区

Why does following code throw exception "Arithmetic operation resulted in an overflow." ?

UInt64[] arr=new UInt64[UInt64.MaxValue];


I guess because totally 8 * UInt64.MaxValue bytes is requested to be allocated, and this multiplication obviously overflows a 64-bit register.


Because indexers only take Int32 values. You can do

UInt64[] arr=new UInt64[Int32.MaxValue];

But thats the limit.

EDIT: Technically you can index an array with value structures that can theoretically be higher than Int32.MaxValue (because you can index an array with a long or a uint for example), however, you will run into that runtime error when the value exceeds Int32.MaxValue.


Because

a) all object are limited to 2GB in .NET
b) You don't have 64 PetaBytes of memory to spend


According to Microsoft's documentation, with framework .NET 4.5 these limitations apply:

  • The maximum number of elements in an array is UInt32.MaxValue.
  • The maximum index in any single dimension is 2,147,483,591 (0x7FFFFFC7) for byte arrays and arrays of single-byte structures, and 2,146,435,071 (0X7FEFFFFF) for other types.
  • The maximum size for strings and other non-array objects is unchanged
0

精彩评论

暂无评论...
验证码 换一张
取 消