-1

I have my "day of the week" for an event stored as a tinyint in SQL Server table. 0 for Sunday, 1 for Monday, etc.

When I pull back a row from the database, I need to use that tinyint value but as a System.DayOfWeek value (whatever the heck that is). I have a function provided to me that uses System.DayOfWeek instead of the numbers 0-6. It returns the next day of the week after today that is provided.

 public static DateTime Next(this DateTime from, DayOfWeek dayOfTheWeek)
        {
            var date = from.Date.AddDays(1);
            var days = ((int)dayOfTheWeek - (int)date.DayOfWeek + 7) % 7;
            return date.AddDays(days);
        }

It errors saying this about the second argument in my function call: "cannot convert from 'byte' to 'System.DayOfWeek'":

DateTime NextEvent;

NextEvent= WorkingDates.DateTimeExtensions.Next(DateTime.Now.Date, item.RecurDayOfWeek);

===========================

At another place in my code close by I try this:

System.DayOfWeek thisDayOfWeek;

thisDayOfWeek = item.RecurDayOfWeek;

and I get this error when I mouse over the right hand side: CS0266: Cannot implicitly convert type 'byte' to 'System.DayOfWeek'. An explicit conversion exists (are you missing a cast?)

I'd like to believe that the solution would have bit me if it was a snake, but I am totally lost at the moment and hope someone can see an answer.

(item.RecurDayOfWeek is the data from the column in the database)


I researched my errors first with the CS code and Microsoft, but the answers were too vague. I also Googled the error messages. Only came here after all failed. It seems so simple and was. I checked the accepted answer.

JustJohn
  • 1,362
  • 2
  • 22
  • 44
  • "as a System.DayOfWeek value (whatever the heck that is)" - Microsoft has some pretty extensive documentation. – Steve Feb 09 '23 at 02:46
  • For example, this page: https://learn.microsoft.com/en-us/dotnet/api/system.dayofweek?view=net-7.0 – Steve Feb 09 '23 at 02:46

2 Answers2

2

Try to explicitly convert it:

byte dayInByte = 6;
var day = (DayOfWeek)dayInByte;
0

Next casts the dayOfTheWeek to an int:

var days = ((int)dayOfTheWeek ...

It looks like you have at least 3 options:

  1. Make Next accept a number: Next(this DateTime from, int dayOfTheWeek)
  2. Call Next with a cast: Next(DateTime.Now.Date, (DayOfWeek)item.RecurDayOfWeek);
  3. Add a Next overload:
    DateTime Next(this DateTime from, int dayOfTheWeek) 
        => Next(from, (DayOfWeek)dayOfTheWeek);
    

BTW. You could additionally make Next use DateOnly to be more precise:

DateOnly Next(DateOnly from, DayOfWeek dayOfTheWeek)
tymtam
  • 31,798
  • 8
  • 86
  • 126