Question

Is there a difference in the returned values between Timespan(0,0,secs) and Timespan.FromSeconds(secs)?

It seems to me the difference is that FromSeconds accepts a double.

Was it helpful?

Solution

Ultimately no, under the hood, TimeSpan deals with ticks.

Personally I would prefer to use TimeSpan.FromSeconds as it is completely clear what the intent is.

OTHER TIPS

The parameter being a double in the second case is an important difference indeed: in some cases it can lead to an OverflowException. Quoting the documentation below.

TimeSpan Constructor (Int32, Int32, Int32):

The specified hours, minutes, and seconds are converted to ticks, and that value initializes this instance.

TimeSpan.FromSeconds Method:

The value parameter is converted to milliseconds, which is converted to ticks, and that number of ticks is used to intialize the new TimeSpan. Therefore, value will only be considered accurate to the nearest millisecond. Note that, because of the loss of precision of the Double data type, this can generate an OverflowException for values that are near but still in the range of either MinValue or MaxValue, This is the cause of an OverflowException, for example, in the following attempt to instantiate a TimeSpan object.

// The following throws an OverflowException at runtime
TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds);

You could test it easily:

int secs = 10;
var ts = new TimeSpan(0, 0, secs);
var ts2 = TimeSpan.FromSeconds(secs);
if(ts == ts2)
{
    Console.WriteLine("Equal");
}
else
{
   Console.WriteLine("Not Equal");
}

Output is: Equal

Even though i find the TimeSpan.FromSeconds method more readable, hence less error-prone, than the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top