Reputation: 7692
Why is there no DateTime.Add(DateTime)
overload when there is a DateTime.Subtract(DataTime)
overload?
Given the similarity of Add and Subtract operations, I would expect they would have the same overloads. Why might this not be the case?
Upvotes: 1
Views: 331
Reputation: 23228
The difference between two DateTime
objects is TimeSpan
object. Subtract(DateTime)
returns TimeSpan
, Subtract(TimeSpan)
returns DateTime
.
However, you can increase DateTime
by TimeSpan
(an interval) value or using AddDays()
, AddMonths()
, etc. methods, adding two DateTime
objects doesn't make sense in terms of result
Upvotes: 5
Reputation: 74605
I agree, it's a deficiency - so let's give a go at sorting it out! :)
static class Ext
{
public static DateTime Add(this DateTime one, DateTime two)
{
return new DateTime(one.Ticks + two.Ticks);
}
}
There are a few things that could go wrong with this, of course, but we'll ignore overflows or timezone issues for a moment. Now we've got the tool, we kinda need to think of a use case for it..
public static void Main()
{
Console.WriteLine("It's " + (DateTime.UtcNow.Add(DateTime.UtcNow)));
}
--> It's 7/1/4038 6:10:06 PM
Hmm.. Soo.. I'll have a think on how to make it useful and get back to you..
Tongue in cheek aside, this is perhaps a good way to demonstrate that if we feel the framework lacks something we need as a simplistic operation, we can add it in as an extension, even if we can't subclass the existing class. It might make sense to be able to find the date half way between two dates, for example:
static class Ext
{
public static DateTime HalfWayTo(this DateTime one, DateTime two)
{
return new DateTime(Math.Abs(one.Ticks + two.Ticks)/2);
}
}
That might have a use case.. And if you think of one for the straight Add, let me know..
Upvotes: 2