I am having a very strange problem. Problem looks funny and simple but its making me mad.
I have a nullable integer in a class which are declared as
public int? count { get; set; }
I have an array of objects(additionalCell) of this class and another object of the same class called currentPixelTotalCell. I want to add values of the count variable of all the objects in the array and store it in the count variable of currentPixelTotalCell.
My code is as below. But when debugging, i see that the left hand part has value as null only after the loop is exited although count variables in all the object have non-null value.
for(int i = 0; i < 5; i++)
{
currentPixelTotalCell.count += additionalCell[i].count;
}
Any idea why is this happening ? Is there a different way to add them ? I am clueless.
Edit:
Forgot to mentioned this. When I have breakpoint and check in first iteration itself, it doesnt add up. Eg. If additionalCell[0].count was 10. Then value of currentPixelTotalCell.count used to be null only even after the inner line was executed in first iteration.
Could it be that you need to initialize the currentPixelTotalCell.count
variable to 0 first?
currentPixelTotalCell.count = 0;
for(int i = 0; i < 5; i++)
{
currentPixelTotalCell.count += additionalCell[i].count;
}
or you may have to check for null values in AdditionalCell objects?
for(int i = 0; i < 5; i++)
{
currentPixelTotalCell.count += (additionalCell[i].count ?? 0)
}