difference between using timespan or integer value representing the timespan in c#

Viewed 558

I have a code where I am calculating some intervals between dates, and to do that I have a defined interval time that I add to one date, to do that I see 2 ways, but I don't understand the difference, for me they are same :

var timespan = new TimeSpan(0, 0, 5);
var d1 = new DateTime(2010, 1, 1, 8, 0, 15);

var newDateWithTimeSpan = d1.Add(timespan);
var newDateWithSeconds = d1.AddSeconds(5);

Console.WriteLine(newDateWithTimeSpan);
Console.WriteLine(newDateWithSeconds);
1 Answers

No, there's no difference between the two ways you're computing the new DateTime value. There are often multiple ways of expressing the same intent, particularly with DateTime. (You could have used d1 + timespan as another option, for example.)

While this isn't the actual implementation, you can imagine that AddSeconds is implemented like this:

public DateTime AddSeconds(double seconds) =>
    this.Add(TimeSpan.FromSeconds(seconds));

It's just a convenience method.

I'd argue that using TimeSpan.FromSeconds in your code is a clearer way of expressing "I want to create a TimeSpan that represents 5 seconds" but that's a slightly separate matter.

Related