Consider the following:
long size = int.MaxValue;
long[] huge = new long[size]; // throws OutOfMemoryException
long[] huge = new long[size + 1]; // throws OverflowException
I know there is a 2GB limit on the size of a single object, which explains the first exception, but why do I get a different exception once the number of elements surpasses 32bits?
(I am using a 64-bit computer if that’s important).
EDIT: I can also define and use an indexer that accepts a long with no problems:
internal sealed class MyClass
{
public object this[long x]
{
get
{
Console.WriteLine("{0}", x);
return null;
}
}
}
...
long size = int.MaxValue;
MyClass asdf = new MyClass();
object o = asdf[size * 50]; // outputs 107374182350
So from what I’ve gathered, something like the following is happening here:
<= Int32.MaxValueand will throw an overflow exception for a value that exceedsInt32.MaxValue.While the latter point feels like some kind of weird contradiction (accepting types larger than
Int32, but throwing an exception if you happen to actually use any of those extra bits), it is apparently a side-effect of the fact that some of this is half-implemented for the future implementation of arrays which will be allowed to have more thanInt32.MaxValueelements.