Search code examples
c#enumsdayofweek

Math with Enums (e.g. DayOfWeek) in C#


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'")


Solution

  • To expand upon what Lasse said (or rather, make it a little more explicit).

    Because 0 is convertable to an Enum type,

    0 - endDate.DayOfWeek becomes 
    (DayOfWeek)0 - endDate.DayOfWeek
    

    And since you can subtract one enum from another and get an integer difference:

    (DayOfWeek)0 - endDate.DayOfWeek == (int)endDate.DayOfWeek
    

    Thus, since the result of the subtraction is an int, you can then add 7 to it.

    endDate.AddDays(0-endDate.DayOfWeek + 7);
    

    So, if Monday's Enum value is 1

    0 - endDate.DayOfWeek == -1 + 7 == 6
    

    However, you can't do the reverse.

    endDate.DayOfWeek - 0 + 7, 
    

    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.

    int enumValue = -(0 - endDate.DayOfWeek);