I am using an int array to hold a long list of integers. For each element of this array I want to check if it is 1, if so do stuff relevant to 1 only, else if it is a 2, do other stuff relevant to 2, and so forth for each value stored in the array. I came up with the code below but it isn’t working as expected, is there something I am missing? What is happening is that only the first value of the array is being considered.
int[] variable1 = MyClass1.ArrayWorkings();
foreach (int i in variable1)
{
if (variable1[i] == 1)
{
// arbitrary stuff
}
else if (variable1[i] ==2)
{
//arbitrary stuff
}
}
You’re trying to do something that doesn’t make sense. To see how it works, take a simple example, an array with values: 9, 4, 1.
If you try to run your code on this sample array, you’ll get an error:
Instead, this is what you need:
The alternative is to use a for loop, which would give you the indices 0, 1, and 2, like this: