Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Switch/ Case statement with an operator?

Status
Not open for further replies.

dduva

Programmer
May 16, 2001
38
US
Newbie needs some help with case statments.

In the code below I want to see if today's day is less than 26. I get an error with my case statment saying I can't implicitly convert a bool to an int. How would I accomplish this?

int dateOfDay = DateTime.Now.Day;

switch(dateOfDay)
{
case dateOfDay < (26):
return DateTime.Today;
break;

case 27:
...
}
 
dduva,

You can't do this type of comparison in C/C# switch/case (<, >, etc). Your case 27 is correct and that is how you have to compare - just the value. What C# does in your case is
1. it evaluates the expression "dateOfDay <26"
2. it compares that result (true or false) with the variable you "switched" (an int).
You can either combine the switch/case with an if or use a list of explicit values and fall-throughs in your switch.
Example
Code:
if ( dateOfDay < 26 )
  ...
else
  switch( dateOfDay )
   ...
Hope this helps.

Volker/
 
Yeah, the C# language spec says it has to be a constant expression:
msdn said:
switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}
Chip H.

____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top