Home .NET Interesting things you may not have known about C# (Array)

Interesting things you may not have known about C# (Array)

by admin

In a continuation of the article "8 facts you may not have known about C#" describing interesting aspects of the C# language, I present a tiny essay.It’s too bad that some people perceive such articles as "captaincy", discouraging any desire to write, but despite this, a lot of useful information pops up in the comments at times.
So, what do the index search functions in arrays return 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, but after checking the documentation, we are surprised to find that the methods IndexOf(Array …) , if no element is found, they return not -1 , and the lower limit of the array is 1
Two conclusions follow from this :
1. You can create an array that doesn’t start 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 creates an array of of three elements, the indexing starts with -1
The correct code looks like this :

Array array = GetArray();int index = Array.IndexOf(array, 42);if (index != (array.GetLowerBound(0) - 1)){// do something}

I think this feature is designed for .NET languages where the indexing starts with 1.
In addition, the documentation describes a separate case where the lower limit is int.MinValue In this case, the method IndexOf will return int.MaxValue which corresponds to int.MinValue - 1 (overflow).
Thank you all for your attention!

You may also like