In the continuation of the article
"8 facts that you may not have known about C #" describing interesting points of the C # language, I present a tiny sketch. It is unfortunate that some perceive such articles as “captaincy”, discouraging any desire for writing, but despite this, in the comments, sometimes a lot of useful information pops up.
So, what do index search functions return in arrays if an element is not found?
Suppose we have a method that returns an Array:
Array GetArray() { return … }
')
And the code that looks for a number in it:
Array array = GetArray(); int index = Array.IndexOf(array, 42); if (index != -1) { // do something }
Everything is familiar and familiar, but after checking the documentation, we are surprised to find that the
IndexOf (Array ...) methods, in the case of not finding the element, return not
-1
, but the
- 1
.
This leads to two conclusions:
1. You can create an array that starts not with 0.
2. The code above is incorrect.
An example of creating an array not with 0:
Array array = Array.CreateInstance(typeof(int), new int[] { 3 }, new int[] { -1 });
In this example
, an array of three elements is created, the index starts at
-1
.
The correct code is as follows:
Array array = GetArray(); int index = Array.IndexOf(array, 42); if (index != (array.GetLowerBound(0) - 1)) { // do something }
I think this feature is created for .NET languages ​​where indexing starts from 1.
In addition, the documentation describes a separate case where the lower bound is equal to
int.MinValue
. In this case, the
IndexOf
method will return an
int.MaxValue
that corresponds to an
int.MinValue - 1
(overflow).
Thank you all for your attention!