Why is it that the following code won’t work:
endDate.AddDays(7-endDate.DayOfWeek);
While this will:
endDate.AddDays(0-endDate.DayOfWeek + 7);
?
(By “won’t work” I mean results in the following compilation error: “cannot convert from ‘System.DayOfWeek’ to ‘double'”)
To expand upon what Lasse said (or rather, make it a little more explicit).
Because 0 is convertable to an Enum type,
And since you can subtract one enum from another and get an integer difference:
Thus, since the result of the subtraction is an int, you can then add 7 to it.
So, if Monday’s Enum value is 1
However, you can’t do the reverse.
because the result type of the calculation is dependant upon the leftmost side. Thus, while 0 – endDate.DayOfWeek results in an integer, endDate.DayOfWeek – 0 results in an enum DayOfWeek.
Most interestingly, you could use this side-effect to get the value of an enum without casting, though I would consider this hackish and confusing… thus to be avoided.