12

This code is a simplified version of what I'm trying to do:

string day = Thursday;
DateTime dt = DateTime.Now;

if (day == dt.DayOfWeek)
{
     // start the program
}

I need to read a day of the week value from a database, assign it to a string, then compare the string to dt.DayOfWeek to check if the program should execute.

My error is this: "Operator '==' cannot be applied to operands of type 'string' and 'System.DayOfWeek"

Anyone know how to compare a string to a DateTime.DayOfWeek value?

3
  • objects in c# have a .ToString() method, most of the built-in ones actually parse the object inot a string Dec 4, 2012 at 22:51
  • I need to read a day of the week value from a database what would return the DB. a number? or a string?
    – L.B
    Dec 4, 2012 at 22:54
  • The DB returns a string for the day value.
    – Mick
    Dec 4, 2012 at 23:07

4 Answers 4

18

Easiest is to convert enum to string:

if (day == dt.DayOfWeek.ToString())...

Notes:

  • if you can change type of day to DayOfWeek enum you can avoid string comparisons (and its related localization/comparison issues).
  • if you have to use string make sure to decide if case is important or not (i.e. should "thursday" be equal to DayOfWeek.Thursday) and use corresponding String.Equals method.
  • consider converting string to enum with Parse as suggested in other answers: ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)
  • make sure incoming string is always English - if it could be in other languages you'll need to look into manually matching value to one provided in CultureInfo.DateTimeFormat.DayNames.
1
  • 1
    But is not a very good practice. It's better to check the equality with enums directy
    – rpax
    Mar 9, 2014 at 23:49
16

Use Enum.Parse to get the Enum value:

if ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), day) == dt.DayOfWeek)

If you're not sure it's a valid value, there's TryParse<T>:

Enum val;
if (Enum.TryParse<DayOfWeek>(day, out val) && val == dt.DayOfWeek)
4

Try DayOfWeek day = DayOfWeek.Thursday;

2

You can use Enum.TryParse<DayOfWeek>:

string strDay = "Wednesday";
DayOfWeek day;
if (Enum.TryParse<DayOfWeek>(strDay, out day)
    && day == DateTime.Today.DayOfWeek)
{
    // ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.