|
-
Feb 8th, 2011, 05:02 PM
#1
Thread Starter
Junior Member
[RESOLVED] switch statement help
hello, im learning to do switch statements, i get the error a constant value is expected. any suggestions?
Code:
private bool SearchItemChosen()
{
switch(false)
{
case txtName.Text == string.Empty:
return true;
case txtInfoUSA.Text == string.Empty:
return true;
case txtAddress.Text == string.Empty:
return true;
case txtCity.Text == string.Empty:
return true;
case ddlState.SelectedValue == string.Empty:
return true;
case txtZip.Text == string.Empty:
return true;
case txtPhone.Text == string.Empty:
return true;
case ddlMCO.SelectedValue == string.Empty:
return true;
default:
return false;
}
}
-
Feb 8th, 2011, 05:27 PM
#2
Re: switch statement help
You have to create "case" on something that can be compiled at compile-time not at run-time. (Checking the contents of a text index is a runtime check. System.Empty could be compile time, but you'd have to do that with something like switch(txtbox.Text)
What you're trying to do isn't cause for a switch anyway.
This is better:
Code:
private bool SearchItemChosen()
{
return
txtName.Text == string.Empty ||
txtInfoUSA.Text == string.Empty ||
txtAddress.Text == string.Empty ||
txtCity.Text == string.Empty ||
ddlState.SelectedValue == string.Empty ||
txtZip.Text == string.Empty ||
txtPhone.Text == string.Empty ||
ddlMCO.SelectedValue == string.Empty;
}
Though it would seem that you might want to be doing != instead of ==
(this function will return TRUE if something was left empty which seems to be the opposite of what the function name implies.)
Need to re-register ASP.NET?
C:\WINNT\Microsoft.NET\Framework\v#VERSIONNUMBER#\aspnet_regiis -i
(Edit #VERSIONNUMBER# as needed - do a DIR if you don't know)
-
Feb 8th, 2011, 05:29 PM
#3
Re: switch statement help
A C# 'switch" statement is not as flexible as a VB Select Case statement. As the error message states, a 'case' statement can contain only constant values, not expressions that require evaluation. You should just be using an 'if' statement with multiple conditions ORed together.
If you want to learn how to use a 'switch' statement then use it in circumstances that it's intended for. You evaluate a single expression and then compare the result to multiple constant values, not a single constant value compared to the result of multiple expressions.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|