For example, I need the first element of the array to have index 3 and not 0
- Et why do you need such perversions? - ThisMan
- Such a task from the teacher) - Mykola Tolkachov
- msdn.microsoft.com/ru-ru/library/… - vp_arth
- In the array is unlikely, but in the collection you can. Set the index offset in the collection indexer. Those. inherit, for example from List <T>, and replace the indexer. - klutch1991
- fourProbably the teacher is also sitting here) - JVic
3 answers
To create an array whose initial index is not 0, you need to use the Array.CreateInstance method
One of the overloads of this method allows you to set lowerBound (initial index)
An example of creating an array of 10 integers with a starting index of 3 may look like this:
var arr = Array.CreateInstance(typeof(int), new[] { 10 }, new[] { 3 }); An obvious problem with such an array is that it may not be as convenient to work with as with zero-based .
At a minimum, to fill an array, instead of using an index, you must use the SetValue method , by analogy, you must use the GetValue method to get the value.
But it can still be used with the foreach operator.
foreach (var item in arr) { Console.WriteLine(item); } An example of filling such an array:
for (int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0); i++) { arr.SetValue(i % 3, i); } The example uses the GetUpperBound and GetLowerBound functions, which return the initial and final indices for the selected dimension respectively (0 for a one-dimensional array). Since these functions return valid indexes, the condition in the loop includes an upper bound.
An alternative fill method may be the Copy method .
For example:
Array.Copy(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }, arr, 10); Herewith: arr[3] == 1 , arr[4] == 2 , etc.
This is possible by overloading Array.CreateInstance
An array of 5 elements, the initial index is 2:
Array arrayObject = Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 2 } The fact is that in C # there is no possibility to overload the operator [] . But it is possible to determine your indexer.
Example of defining a custom indexer:
class MyArr { int[] arr; public int Length; public MyArr(int Size) { arr = new int[Size]; Length = Size; } public int this[int index] { get { return arr[index]; } set { arr[index] = value; } } }