Alan
Alan

Reputation: 7951

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

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.

Upvotes: 4

Views: 130

Answers (2)

famousgarkin
famousgarkin

Reputation: 14126

There is a way to create an Array with negative indexes in .NET, using this overload of Array.CreateInstance factory method, where you can specify the lower bound of the index:

public static Array CreateInstance(
    Type elementType,
    int[] lengths,
    int[] lowerBounds
)

A 1-dimensional array with length of 10 and index starting at -10:

var a = Array.CreateInstance(typeof(string), new[] { 10 }, new[] { -10 });
a.SetValue("test", -5);
Console.WriteLine(a.GetValue(-5));
Console.WriteLine(a.GetLowerBound(0));

// yields:
// test
// -10

Also note that a 1-dimensional array with negative index lower bound cannot be cast to a vector, such as int[], which must be 0-based indexed. This kind of array is of different type than vector or 0-based indexed array:

Console.WriteLine((Array.CreateInstance(typeof(int), new[] { 1 }, new[] { -1 })).GetType());
Console.WriteLine((Array.CreateInstance(typeof(int), new[] { 1 }, new[] { 0 })).GetType());
Console.WriteLine((new int[] {}).GetType());

// yields:
// System.Int32[*]
// System.Int32[]
// System.Int32[]

(int[])Array.CreateInstance(typeof(int), new[] { 1 }, new[] { -1 })

// throws:
// System.InvalidCastException

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

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.

Upvotes: 5

Related Questions