Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Length behavior vs .LongLength when array size is larger than Int32.MaxValue

Tags:

arrays

c#

I'm looking for some documentation on the differences between an array's .Length and .LongLength properties.

Specifically, if the array's length is larger than Int32.MaxValue, will .Length throw an exception, return Int32.MaxValue, go negative, return 0?

(to clear up "possible duplicate" concerns: I'm not asking about the maximum length of an array, or the maximum size of a .NET CLR object. Assume a 64 bit system and a CLR version which supports large objects)

like image 360
DaveD Avatar asked Dec 21 '15 22:12

DaveD


Video Answer


1 Answers

It is not possible to create a one dimensional array having more than 2,147,483,591 elements (for comparison, int.MaxValue is 2,147,483,647). OutOfMemoryException is thrown if an attempt is made to create an array with more elements. It means that the LongLength property is still useless and you can use the Length property instead.

I've tested it on the x64 platform using .NET 4.5. In order to create the array with 2,147,483,591 elements I've modified the configuration file and added:

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

Basically, I used this MSDN page to enable arrays that are greater than 2 (GB) in total size. The real limit for arrays:

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.

like image 145
Sergii Zhevzhyk Avatar answered Sep 28 '22 11:09

Sergii Zhevzhyk