1

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?

Thanks!

2
  • 3
    Also C# arrays are zero indexed, you need change for (int w = 1; w <= 53; w++) to for (int w = 0; w < 53; w++) Commented Aug 4, 2016 at 15:23
  • Instead of casting you could also use DataRowExtension.Field: int weekValue = data.Rows[i].Field<int>("week" + w) Commented Aug 4, 2016 at 15:26

4 Answers 4

5

You need to cast object type to integer type

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

also your array iteration for loop logic needs to be updated otherwise index will be outside the range and it will throw IndexOutOfRangeException

for (int w = 0; w < WeeklyTotal.Length; w++)
{
    WeeklyTotal[w] = WeeklyTotal[w] + (int)data.Rows[i]["week" + w];
}
Sign up to request clarification or add additional context in comments.

Comments

2

if the object really is a boxed integer use (int) Cast operator else use Convert.ToInt32()

1 Comment

Yes, Convert is a better alternative to cast in the context: data.Rows[i] can well return boxed short or, say, String (e.g. "123 ") if database field is of wrong type etc.
1

Need to cast object type as an integer:

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

Comments

1

As others already pointed out, you have to cast the object returned by data.Rows[i]["week" + w] to int.

But more important your for loop is buggy and will cause an IndexOutOfRangeException.

Arrays are zero-indexed in c#, so your loop should run from 0 to 52 or you have to decrease w by one when accessing the array:

int[] WeeklyTotal = new int[53];
for (int w = 1; w <= 53; w++)
{
    WeeklyTotal[w-1] = WeeklyTotal[w-1] + (int)data.Rows[i]["week" + w];
}

or

int[] WeeklyTotal = new int[53];
for (int w = 0; w < 53; w++)
{
    WeeklyTotal[w] = WeeklyTotal[w] + (int)data.Rows[i]["week" + (w+1)];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.