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

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

Why is this indicated in the documentation and how is this possible?

This method does not support search arrays containing negative indexes. the array must be sorted before calling this method.

+4
source share
2 answers

You can create an array that allows you to add 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 ideon.

, int[], CLR . API Array. , BinarySearch.

+5

Array .NET, Array.CreateInstance factory method, :

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

1- 10 , -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

, 1- , int[], 0. , 0:

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
+2

Source: https://habr.com/ru/post/1545878/


All Articles