use of unassigned local variable `total`

Nick_BE picture Nick_BE · Oct 24, 2011 · Viewed 7k times · Source

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);
}

Answer

CodesInChaos picture CodesInChaos · Oct 24, 2011

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.