Home > Net >  C# fixed size array, getting maximum index [closed]
C# fixed size array, getting maximum index [closed]

Time:10-04

In C#, if I declare an array: int[] arr = new int[3] is there a way to retrieve the maximum possible index/length? And, no. I'm not looking for arr.Length which would be 0

I'm looking to get the number 2 or 3. Something like: arr.maxSize

Does something like this exist?

CodePudding user response:

arr.Length works - for the record, just tested:

int[] arr = new int[3];

var length = arr.Length;  // length = 3 as it was expected

arr[2] = 2; // Ok

arr[3] = 3; // Out of range exception, as it was expected, 3 is a max size.

CodePudding user response:

For your one-dimensional array arr you can use:

  • var lwr = arr.GetLowerBound(0); to get the lowest index;
  • var upr = arr.GetUpperBound(0); to get the highest index.

See https://docs.microsoft.com/en-us/dotnet/api/system.array?view=net-5.0 for more info.

  • Related