-3

I would like to change in an existing content one condition to a little bit more flexible and struggel here.:

the original looks like:

if (object.dayofweek == DayOfWeek.Tuesday)
{
}

my first approach was to replace Tuesday by an integer, but this fails. Then I've tried to use:

if (object.dayofweek == Enum.GetName(typeof(DayOfWeek), 2))
{
}

does not work.

Any hint, how I can replace the fixed day by an variable? Thanks!

rytisk
  • 1,331
  • 2
  • 12
  • 19
  • 6
    Replacing a named constant (`Tuesday`) with a [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants) (`2`) is the opposite of being more flexible. What do you [actually](https://meta.stackexchange.com/q/66377/147640) want to achieve? – GSerg Jan 25 '21 at 10:54
  • What type is _object_? I Assume is a DateTime variable but in this case _object.DayOfWeek_ should be correctly capitalized. – Steve Jan 25 '21 at 10:56
  • Does this answer your question? [How can I cast int to enum?](https://stackoverflow.com/questions/29482/how-can-i-cast-int-to-enum) –  Jan 25 '21 at 11:56

2 Answers2

0

You need a way to get the current day of the week. That could be done with

DateTime.Today.DayOfWeek

If you're using that, then you can keep using DayOfWeek.Tuesday, like this:

if (DateTime.Today.DayOfWeek == DayOfWeek.Tuesday)

And in case you want to know how to change an enum to a variable, use (int)DayOfWeek.Tuesday

Steven
  • 1,996
  • 3
  • 22
  • 33
0

(DayOfWeek)myInteger – Klaus Gütter

This is the solution, a simple type conversion.

so the result would be:

if (DateTime.Today.DayOfWeek == (DayOfWeek)2) // for instance in case of Tuesday
Steven
  • 1,996
  • 3
  • 22
  • 33
  • You took someone's comment and made it an answer, when the other answer, along with the comment, solves your problem. You should upvote and accept that answer, not create your own answer from someone else's comment/answer. – David Makogon Feb 20 '21 at 14:51