use of unassigned local variable `total`

7.5k Views Asked by At

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

There are 4 best solutions below

2
On
total += interval;

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

1
On

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

0
On

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.

0
On

You should initialize total value before use

 TimeSpan total = new TimeSpan();,

then code should work.