Casey Crookston Casey Crookston - 5 months ago 13
C# Question

Adding an int to an existing array of its

Here is my code I have tried

int[] WeeklyTotal = new int[53];
for (int w = 1; w <= 53; w++)
WeeklyTotal[w] = WeeklyTotal[w] + data.Rows[i]["week" + w]; // Error is here

But I'm getting a compile error:

Can not apply opperator + to opperands of type int and object

What is the correct syntax here?



You need to cast object type to integer type

WeeklyTotal[w] = WeeklyTotal[w] + (int)data.Rows[i]["week" + w]; 

also your array access for loop logic need to be update otherwise index will go outside the boundary and will throw IndexOutOfRangeException

for (int w = 0; w < WeeklyTotal.Length; w++)
    WeeklyTotal[w] = WeeklyTotal[w] + (int)data.Rows[i]["week" + w];