3

I want to have a sum of all intervals , but I write this code I have an error stating: use of unassigned local variable total ?

enter TimeSpan total;
foreach (var grp in query)
{
  TimeSpan interval = TimeSpan.FromMinutes(grp.Minuut); 
  TimeSpan intervalH = TimeSpan.FromHours(grp.Sum);

  interval = interval + intervalH;
  total += interval;
  string timeInterval = interval.ToString();   
  dataGridView2.Rows.Add(i++, grp.Id, grp.Sum, grp.Minuut,timeInterval);
}
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
Nick_BE
  • 127
  • 2
  • 8

4 Answers4

7

Start with:

TimeSpan total = TimeSpan.Zero;

Incrementing a variable that has no value makes no sense. So it's only natural for this to be a compiler error.

While fields get initialized to 0, local variables must be assigned to before they are first read. In your program total += interval; reads total in order to increment it. In the first iteration of your loop it thus wouldn't have been assigned a value.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1
total += interval;

Is wrong when total has no value assigned at all... What are you going to add interval too?

FailedDev
  • 26,680
  • 9
  • 53
  • 73
1

You should initialize total value before use

 TimeSpan total = new TimeSpan();,

then code should work.

Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
0

No initial value is ever assigned to total. You have to assign a value before you use it.

dnuttle
  • 3,810
  • 2
  • 19
  • 19