Why is “long” being allowed as array length in C#?

邮差的信 提交于 2019-11-29 03:30:19

Because the specification says so in section 7.6.10.4:

Each expression in the expression list must be of type int, uint, long, or ulong, or implicitly convertible to one or more of these types.

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 int by the way: There is also LongLength, returning a long. This was in .NET 1.1 and probably a future-proofing change.

Md Kamruzzaman Sarker

why long is allowed as array length?

Answer is: long in .net means Int64

And array indexing can be Int64 according to specification.

2nd question: Why overflowexception is showing?

Because any single object can not be allocated more than 2GB of memory.

Adam Houldsworth

It is a limitation of the CLR, no single object can exceed 2GB, including arrays:

Large array C# OutOfMemoryException

This is regardless of 32-bit or 64-bit OSs. That said, it doesn't stop you from using more than that amount in total, just not on one object.

It is a runtime error because if you keep the long (or other initializing value) within range, it will work.

You can initialize arrays with all integral types: sbyte, char, short, int, and long - all compile; the unsigned variants work too.

There is a solution in .Net 4.5-4.6 for allowing large size for an array.

<runtime>
    <gcAllowVeryLargeObjects enabled="true" />
</runtime>

https://msdn.microsoft.com/en-us/library/hh285054(v=vs.110).aspx

The long is an integral type, so it can be used to define the array; the exception is from building too large of an array, not specifically from using a long.

Ex, this works just fine:

long size = 20;
byte[] array = new byte[size];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!