Why isn't my TimeSpan.Add() working?
Asked Answered
C

4

29

There has to be an easy answer:

var totalTime = TimeSpan.Zero;

foreach (var timesheet in timeSheets)
{
   //assume "time" is a correct, positive TimeSpan
   var time = timesheet.EndTime - timesheet.StartTime;
   totalTime.Add(time);
}

There's only one value in the list timeSheets and it is a positive TimeSpan (verified on local inspection).

Crap answered 27/8, 2010 at 2:33 Comment(1)
For a different approach, you can accomplish all that with this: var totalTime = timeSheets.Sum(sheet => sheet.EndTime - sheet.StartTime);Housebound
B
79

TimeSpans are value types. Try:

totalTime = totalTime.Add(time)

Bellaude answered 27/8, 2010 at 2:37 Comment(0)
S
28

This is a common mistake. TimeSpan.Add returns a new instance of TimeSpan.

Setback answered 27/8, 2010 at 2:36 Comment(0)
T
7
totalTime = totalTime.Add(time)
Terri answered 27/8, 2010 at 2:37 Comment(0)
P
0

TimeSpans are value types and can use the += operator similar to integral and floating point numeric types. I find the += operator neat to use in this situation which is the same as writing x = x + y.

var totalTime = TimeSpan.Zero;

foreach (var timesheet in timeSheets)
{
   totalTime += (timesheet.EndTime - timesheet.StartTime);
}
Postaxial answered 24/10, 2022 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.