Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Array.BinarySearch mean when it says an array with negative indexes?

Tags:

arrays

c#

.net

The documentation for Array.BinarySearch in .NET says that it does not work for an array that has negative indexes. As far as I know, .NET only has arrays with positive indexes and you are not allowed to inherit from the System.Array type.

Why does the documentation state this and how is it possible?

This method does not support searching arrays that contain negative indexes. array must be sorted before calling this method.

like image 839
Alan Avatar asked Mar 20 '23 05:03

Alan


1 Answers

You can create an array that lets you supply negative indexes to your array:

var grid = (int[,])Array.CreateInstance(typeof(int),new[] {7,7}, new[] {-3,-3});
for (int r = -3 ; r <= 3 ; r++) {
    for (int c = -3 ; c <= 3 ; c++) {
        grid[r,c] = 10+r + c;
    }   
}

Demo on ideone.

You can make an array with a single dimension, too, but you wouldn't be able to convert it to int[] because CLR uses a special type for one-dimension arrays. However, you could use such array with negative indexes through the Array API. The documentation says that you are not allowed to pass such arrays to the BinarySearch method.

like image 131
Sergey Kalinichenko Avatar answered Apr 09 '23 16:04

Sergey Kalinichenko