tags:

views:

116

answers:

2
TimeSpan span = TimeSpan.Zero;
span.Add(TimeSpan.FromMinutes(5));
Console.WriteLine(span.TotalSeconds);   -----> will out put "0"

however

TimeSpan span = TimeSpan.Zero.Add(TimeSpan.FromMinutes(5));
Console.WriteLine(span.TotalSeconds);   -----> will out put "300"

Does anyone see this before???

+12  A: 

TimeSpan is a struct. TimeSpan.Add does not modify the input - it returns a new TimeSpan which is the input plus the addend:

Remarks

The return value must be between TimeSpan.MinValue and TimeSpan.MaxValue; otherwise, an exception is thrown.

The return value is a new TimeSpan; the original TimeSpan is not modified.

John Saunders
It even says that in the documentation for TimeSpan.Add (http://msdn.microsoft.com/en-us/library/system.timespan.add.aspx): The return value is a new TimeSpan; the original TimeSpan is not modified.
Jonathan
However, it should be noted that it’s not *because* `TimeSpan` is a struct. It’s because `TimeSpan` is *immutable*. `System.Drawing.Point` is an example of a struct that is not immutable. `string` is an example of an immutable type that is not a struct.
Timwi
-1 for unrelated and misleading "`Timespan` is a struct" phrase.
tia
A: 

Not a bug in Timespan but.... in the way structures get copied in C#.

TomTom
-1: not a bug at all. It's clearly documented.
John Saunders
@TomTom: How so?
Esteban Araya
@John Saunders: Don't think this deserves a down vote. The answer does state that it is not a bug. Pretty much the same answer you gave just a lot more brief.
Dieter G
It would be a bug if Timespan was a class, but as a struct this is expected behaviour. That is, classes are passed by reference, so whatever the receiving method does to the passed class are visible at a calling level. A struct however is passed by value, so receiving methods cannot communicate changes made to the passed in method. To communicate changed values either out parameters or return values need to be used.
Tim Joseph
@Dieter, TomTom let TimeSpan off the hook only to put C# structs in a bag and then hang them all. If not worth a downvote, the answer clearly begs for more detail.
Anthony Pegram
@Tim, pass by reference/value has nothing to do with this. Struct vs. Class has nothing to do with this. This is about immutability. It is perfectly legal (however frowned upon) to create a mutable struct and have a method on that struct modify it. TimeSpan is not such a struct.
Anthony Pegram
In fact, it’s not even directly because of immutability. It’s simply because of the contract of the `TimeSpan.Add` method. Of course, in the case of `TimeSpan` that contract was chosen in order to achieve immutability — but you could equally well have a similar `Add` method on a type that is otherwise mutable.
Timwi