I wanted to try to allocate a 4 billion bytes array and this is my C# code:
long size = 4 * 1000;
size *= 1000;
size *= 1000;
byte[] array = new byte[size];
this code fails with System.OverflowException on the line containing new. Okay, turns out Length returns int, so the array length is also limited to what int can store.
Then why is there no compile-time error and long is allowed to be used as the number of array elements at allocation?
Because the specification says so in section 7.6.10.4:
This is most likely to easily allow creation of arrays larger than 2 GiB, even though they are not supported yet (but will be without a language change once the CLR makes such a change). Mono does support this, however and .NET 4.5 apparently will allow larger arrays too.
Regarding array length being an
intby the way: There is alsoLongLength, returning along. This was in .NET 1.1 and probably a future-proofing change.