I am try to make a test to see all columns in rows in a array are the same number but i keep on getting
Argument 1: cannot convert from ‘int[,]’ to ‘int[][]’ CS1503
using System;
public class Program
{
public static void Main(string[] args){
testing Test = new testing();
if(Test.test(Test.array) == true){
//code
}
}
}
class testing{
public int[,] array = {{10,0,25,7},
{5,0,30,10}};
public bool test(int[][] array){
int count = 0;
for (int i = 0; i < array.GetLength(1); i++){
if(array[i][4] <= 0){
count++;
}
}
return count == array.GetLength(1);
}
}
I tried to change test(int[][] array)
to test(int[,] array)
to get rid of the error but instead I get
Wrong number of indices inside []; expected 2 CS0022
I already got two indices but the error highlights array[i]
.
3
There are several problematic issues in your code:
int[][]
andint[,]
are different. You need to choose one of them and be consistent.
I’ll assume you pickedint[,]
for the rest of the answer, but it could be adapted toint[][]
.- When you access an
int[,]
element you should useoperator[,]
(not[][]
) – soarray[i][j]
should bearray[i,j]
. - Array indices are zero based, and so
array[i][4]
(even if you chooseint[][]
will go out of bounds – the second index should be in the range 0..3. - Array dimensions are also zero based. In your outer loop you seem to attempt to iterate over the first dimension, so you have to use
array.GetLength(0)
, notarray.GetLength(1)
. - This is not causing an immediate error, but
array
is rather a bad name as it could cause conflicts, it is better to choose another name (e.g.arr
).
A fixed version:
public class Program
{
public static void Main(string[] args)
{
testing Test = new testing();
if (Test.test(Test.arr) == true)
{
//code
}
}
}
class testing
{
public int[,] arr = {{10,0,25,7},
{5,0,30,10}};
public bool test(int[,] arr)
{
int count = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
if (arr[i,3] <= 0)
{
count++;
}
}
return count == arr.GetLength(0);
}
}
Side notes:
- You mentioned that you want to test to see if all columns in rows in a array are the same number. But the logic you posted is quite different.
Anyway based on the comments above you can modify the logic according to your needs. - Your
test
method code does not actually access thearray
member, but rather the method parameter.
Therefore you can either make it astatic
method, or remove thearray
parameter so that the method will access the member.