0

I'm trying to use a boolean array with 10000 elements & my program is erroring out as the number of elements coming into my file load are more than 10000.

Is there a max limit restriction on boolean array size in C#? For my project I need to allocate 1 million elements. Something like Boolean[] testBoolArray = new Boolean[1000000]. Will that cause any issue?

TomFL
  • 1
  • You can have up to 2^31 elements so it would work just fine, but you might want to consider using [class `BitArray`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=net-7.0) if you are worried about memory usage. Also if you use a `List` it can grow to the size you need without you needing to overallocate the size. – Matthew Watson Aug 18 '23 at 15:37
  • Not quite related to your question, but arrays that take up more than 85k of memory will be allocated in the _Large Object Heap_. That's ok, but it can mess up your program (by provoking Gen2 GC collections) if you allocate and let them be collected often. – Flydog57 Aug 18 '23 at 16:14

1 Answers1

0

Is there a max limit restriction on boolean array size in C#?

Yes, see Array.MaxLength:

This property represents a runtime limitation, the maximum number of elements (not bytes) the runtime will allow in an array. There is no guarantee that an allocation under this length will succeed, but all attempts to allocate a larger array will fail.

This should in most cases be equal to int.MaxValue, or 2147483647. So a million elements should work just fine unless you are running in a very memory restricted environment.

A more likely reason for your problems is that the number of elements are more than you are expecting. So some operation is giving an error since the array is not large enough to hold all elements.

A common way to store variable size data in a file on disk is to prefix the data with the length, something similar to:

public static bool[] ReadBoolArray(BinaryReader reader){
   var length = reader.ReadInt32();
   var result = new bool[length];
   for(var i = 0; i < length; i++){
      result[i] = reader.ReadBoolean();
   }
   return result;
}

You may have issues if either the file does not include the number of items in the array, you are mistaken about the format the file stores the data in, or if the file is somehow corrupt.

JonasH
  • 28,608
  • 2
  • 10
  • 23