I understand a similar question has been asked many times and answered as well.
Much of the articles on internet point to only one answer i,e. max of int value or 2147483647.
Inline are couple of links from stackoverflow:
What is the Maximum Size that an Array can hold?
Maximum size of string array in C#
However, when I tried to check the same an OutOfMemoryException is thrown. In fact I tried to reduce the size by a factor of 2 to 1073741823(throws exception), factor of 4 to 536870911(throws exception), factor of 8 to 268435455 (program executes well without any exception).
Test Code:
using System;
namespace ConsoleApp
{
class Program
{
static void Main()
{
int arraySize = Int32.MaxValue / 1; //Factor when set to 8, program executes without any exception
int[] testArray = new int[arraySize];
testArray[0] = 6;
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
}
Looks like all the other answers point to a theoretical value which is `2147483647. However in practice this is not always the case. So the question is, given the application code is very simple with just one array and couple of calls to console, is it possible to figure out at what size of array the application will throw an OutOfMemoryException.
gcAllowVeryLargeObjects? The point is that your application needs to be able to allocate a contiguous amount of arraySize*elementSize of RAM. If it can't, it'll fail. AFAIK it's not trivial using managed code to predict whether that will succeed. What do you need that large an array for anyway?Memory<T>/Span<T>) is a better idea.