3

I'm reviewing some code and found this bit (rewritten):

if ((int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(someDate) == 7) ...

I would think this condition always returns false since DayOfWeek (the return type) ranges from 0 to 6, or could this eventually return 7 in a specific culture?

Koen
  • 3,626
  • 1
  • 34
  • 55

3 Answers3

3

The DayOfWeek enumeration represents the day of the week in calendars that have seven days per week. The value of the constants in this enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If cast to an integer, its value ranges from zero (which indicates DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).

Source - http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
  • I know (and read) that obviously. Still enumerations allow other values than the predefined values, e.g. '(DayOfWeek)7' works at compile-time and run-time so I'm confused as if this bit of code actually makes sense at some point... – Koen Feb 03 '11 at 14:09
2

Did you take a look at the DayOfWeek enum page on MSDN?

The DayOfWeek enumeration represents the day of the week in calendars that have seven days per week. The value of the constants in this enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If cast to an integer, its value ranges from zero (which indicates DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
1

Normally GetDayOfWeek will never return a (converted) value 7.

From the code it is very unclear what the programmer wants. I suggest rewriting it as:

if (CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(someDate) == DayOfWeek.Saturday) ...

Or something.

GvS
  • 52,015
  • 16
  • 101
  • 139
  • Actually they reuse the day number to find the previous Monday with AddDays(...), so I guess I still need it (just remove the if-statement). Unless you know a cleaner way to find the previous Monday? – Koen Feb 03 '11 at 14:12
  • I use: (today = DateTime variable that contains date): `var lastMonday = today.DayOfWeek == DayOfWeek.Sunday ? today.AddDays(-6) : today.AddDays(-(int)today.DayOfWeek).AddDays(1);` – GvS Feb 03 '11 at 15:44