This question already has answers here:
Variable declaration in a C# switch statement [duplicate]
(7 answers)
Case Statement Block Level Declaration Space in C#
(6 answers)
Closed 3 years ago.
I was surprised to discover that locals in switch statements are scoped to the switch statement and not to the case. Why is that? And is it good practice to add curly braces around each case as a workaround.
This won't compile:
switch (n)
{
case 1:
var i = 1;
Console.WriteLine(i);
break;
default:
var i = 2;
Console.WriteLine(i);
break;
}
This does compile:
switch (n)
{
case 1:
{
var i = 1;
Console.WriteLine(i);
break;
}
default:
{
var i = 2;
Console.WriteLine(i);
break;
}
}
This is a design choice specifically made by C#.
A variable only exists inside the innermost braces in which the variable is first declared. This makes it easy to check the variables scope just by looking, and I might guess it also makes parsing easier
Related
This question already has answers here:
'||' operators to be used between two enums in a switch statement
(1 answer)
How to use && operator in switch statement based on a combined return a value?
(5 answers)
c# - case statement for logical operators
(2 answers)
Closed 1 year ago.
I'm C# beginner. Why appear the error (Compiler Error CS0152, A label was repeated in a switch statement. The switch statement contains multiple cases with the value of tag '6') in "case 6:" line, when I write this code:
namespace ConsoleApp1
{
class Class1
{
public int abc { get; set; }
public Class1()
{
}
public void mTest(int aVal)
{
switch(aVal)
{
case (2 | 4):
{
break;
}
case 5:
{
break;
}
case 6:
{
break;
}
}
}
}
}
You're almost there, but the correct way to pattern match that condition is:
case 2 or 4:
break;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a method, inside this method, at first, I use switch-case like this:
public int setDeviceName
{
set
{
device_id = value;
DeviceNoList[(page_no - 1) * display_data_num + selectedTagNo - 1] = value;
switch (selectedDeviceNo)
{
case 1:
lblLocation1.Text = lblDeviceName_Selected(device_id);
break;
case 2:
lblLocation2.Text = lblDeviceName_Selected(device_id);
break;
case 3:
lblLocation3.Text = lblDeviceName_Selected(device_id);
break;
case 4:
lblLocation4.Text = lblDeviceName_Selected(device_id);
break;
case 5:
lblLocation5.Text = lblDeviceName_Selected(device_id);
break;
case 6:
lblLocation6.Text = lblDeviceName_Selected(device_id);
break;
case 7:
lblLocation7.Text = lblDeviceName_Selected(device_id);
break;
case 8:
lblLocation8.Text = lblDeviceName_Selected(device_id);
break;
default:
break;
}
}
get
{
return device_id;
}
}
After, I tried to do For loop instead like below:
public int setDeviceName
{
set
{
device_id = value;
DeviceNoList[(page_no - 1) * display_data_num + selectedTagNo - 1] = value;
Label [] lbl_Location = { lblLocation1, lblLocation2, lblLocation3, lblLocation4, lblLocation5, lblLocation6, lblLocation7, lblLocation8 };
//set deviceName to each label in form
for(int i = 0; i<display_data_num; i++)
{
lbl_Location[i].Text = lblDeviceName_Selected(device_id);
}
}
get
{
return device_id;
}
}
I have checked, my program still goes well, I don't know Can I use For instead of Switch-case like that or not. If not, why my program still work. I am new in programming.
A for loop is better than switches and ifs when there are many different cases, all being a number in order. There are many reasons why but the best is: which is easier to read and write? 100 lines of cases or a few lines if a for loop?
In this scenario if you can change it to be in this form, it will be much better. We cannot move it straight over how you wanted, though, because indexing ([i]) doesn't work how you seem to think it does. Indexing grabs the value at the specified index of the collection, maybe an array, a list, etc..
If we change our lbl_Location1, ... to an array:
string[] lbl_Location = new string[]{ "a value 1", "a value 2", "and more" };
Obviously change the strings to the value and type of your choice. You can then do what you want and iterate through the indexes, which is better. Note that indexes start at 0! The first value is 0, second 1, etc..
Implementation (notice I changed your condition in the for statement to the length of the array, this is a cleaner and simpler way to do it. Unless you were doing something different where that wasn't just the length of the array, just stop using that and use this):
for(int i = 0; i<lbl_Location.Length; i++)
{
lbl_Location[i].Text = lblDeviceName_Selected(device_id);
}
If you don't understand something or I misunderstood please comment!
More information on indexing:
So let's say I have a variable called MyString1. What you were trying to do with MyString[1] (I have replaced i with a 1 to further simplify this) is "look for a (for simplicity's sake) array called MyString and look at the second (remember, indexes start at zero!) position." What you wanted it to do was just add a 1 at the end. When we make it an array, we are essentially making one variable that is a container for many values.
This question already has answers here:
Multi-variable switch statement in C#
(13 answers)
Closed 8 years ago.
Is it possible to return result from multiple switch statement?
For example i would like to use employee.DepartmentID and employee.StatusID for my case. But how do i include employee.StatusID in this statement? Using and/or operators?
switch (employee.DepartmentID)
{
case 1:
EMAIL = "abc#gmail.com";
break;
case 2:
EMAIL = "abcd#gmail.com";
break;
}
What you really need is this.
Use the Switch to determine which department is involved
Switch (DepartmentID)
{
case 1:
Email = classHR.GetEmailAddress(Status);
break;
case 2:
Email = classMarketing.GetEmailAddress(Status);
break;
}
Use Static Classes for the different departments (using an interface preferably).
This will give you a better run down than what you are thinking of here.
This question already has answers here:
Break out of a while loop that contains a switch statement
(15 answers)
Closed 8 years ago.
I was asked to do maintenance work on some C# code which, I'm told, was originally converted from Visual Basic 6. (I mention this only because I don't know VB6 so I don't know if it would have made more sense in that language. . .)
It's got a for loop which parses some text for a proprietary scripting language by using a switch inside the for loop . . .
for ( t = 0; t < upperBound(tokens); t++)
{
String mystring = tokens[t];
switch (mystring)
{
case "GOTO":
if (firstGoto == -1)
{
firstGoto = t;
}
else
{
// compute number of tokens in GOTO
pointLength = t - firstGoto - 1;
break; // exit for
}
break;
case "ACTUATE"
. . .
Notice the comment
// exit for
The programmer expects the break will exit the for loop but I think it will only exit the switch statement because the documentation for break says
The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.
So am I correct that this will only exit the switch, but still be in the for, and if so, what is the correct way to do what the original programmer intended?
Yes, break will break out of the closest loop or switch. The easiest way is to use a goto. (No, goto is not evil)
for {
switch(...) {
....
goto MyLabel;
}
}
MyLabel:
Yes, you are correct... break will only exit the innermost block of code.
One easy way to do this is to also have a boolean flag which is set within the switch statement, and at the end of the loop just do this:
var flag = false;
for (...) {
switch (...) {
case "x":
flag = true;
}
if (flag) break;
}
Yes break will only terminate the switch in this scenario. How about using a boolean to exit the for as well..?
for ( t = 0; t < upperBound(tokens); t++)
{
String mystring = tokens[t];
bool exitFor = false;
switch (mystring)
{
case "GOTO":
if (firstGoto == -1)
{
firstGoto = t;
}
else
{
// compute number of tokens in GOTO
pointLength = t - firstGoto - 1;
exitFor = true;
break; // exit for
}
break;
case "ACTUATE"
. . .
if(exitFor)
break;
This question already has answers here:
How to make C# Switch Statement use IgnoreCase
(12 answers)
Closed 9 years ago.
C#'s switch() statement is case-sensitive. Is there a way to toggle it so it becomes case-insensitive?
==============================
Thanks,
But , I don't like these solutions;
Because case conditions will be a variable , and I don't know if they ALL are UPPER or lower.
Yes - use ToLower() or ToLowerInvariant() on its operands. For example:
switch(month.ToLower()) {
case "jan":
case "january": // These all have to be in lowercase
// Do something
break;
}
You can do something like this
switch(yourStringVariable.ToUpper()){
case "YOUR_CASE_COND_1":
// Do your Case1
break;
case "YOUR_CASE_COND_2":
// Do your Case 2
break;
default:
}
Convert your switch string to lower or upper case beforehand
switch("KEK".ToLower())
{
case "kek":
CW("hit!");
break;
}