C# Switch statement scenario - c#

UPDATED:
Is there a way to accomplish what the code below attempts to do (doesn't pass syntax because case 2 and case 3 can't have duplicate declarations and/or because num can't be 2 and 3 at the same time)?
var num = 0;
switch (num)
{
case 1:
//do stuff applicable to 1 only;
break;
case 2:
//do stuff applicable to 2 only;
break;
case 3:
//do stuff applicable to 3 only;
break;
case 2:
case 3:
//do stuff applicable to 2 and 3 only;
break;
}

The question is confusingly posed. I think what you want is to have a case that runs for two, a case that runs for three, and a case that runs for two-or-three.
Just use two switches:
switch (num)
{
case 1: One(); break;
case 2: Two(); break;
case 3: Three(); break;
}
switch (num)
{
case 2:
case 3: TwoOrThree(); break;
}
Or
switch (num)
{
case 1: One(); break;
case 2:
case 3:
switch (num)
{
case 2: Two(); break;
case 3: Three(); break;
}
TwoOrThree();
break;
}
Or duplicate the code:
switch (num)
{
case 1: One(); break;
case 2: Two(); TwoOrThree(); break;
case 3: Three(); TwoOrThree(); break;
}
I would NOT recommend un-duplicating the code like this:
switch (num)
{
case 1: One(); break;
case 2: Two(); goto twoOrThree; break;
case 3: Three(); twoOrThree: TwoOrThree(); break;
}
Yuck.

not with a single-level switch (or a nasty GOTO). A switch can only execute one case. A better solution would be a nested if (or switch) within the 2/3 case:
switch (num)
{
case 1:
//do stuff applicable to 1 only
break;
case 2:
case 3:
if(num == 2)
{
//do stuff applicable to 2 only
}
if(num == 3)
{
//do stuff applicable to 3 only
}
//do stuff applicable to 2 OR 3
break;
}

It's as simple as this...
switch (value)
{
case 1:
// Do 1 stuff
break;
case 2:
case 3:
// We can use an if-else construct here given that there's only two possibilities.
if (value == 2)
{
// 2 only stuff here
}
else
{
// 3 only stuff here
}
// Do anything applicable to BOTH here, or above the if construct, depending on your requirements.
break;
default:
// Any other stuff here
break;
}
Or just use an if construct, which is arguably cleaner (switch is really only intended for simple many to one logical mappings)...
if (value == 1)
{
// 1 stuff
}
else if (value == 2 || value == 3)
{
if (value == 2) {
// 2 stuff only
}
else
{
// 3 stuff only
}
// 2 or 3 stuff, or above the if construct above, if you require.
}
else
{
// Anything else here
}
Or simply...
switch (value)
{
case 1:
OneStuff();
break;
case 2:
TwoStuff();
TwoOrThreeStuff();
break;
case 3:
ThreeStuff();
TwoOrThreeStuff();
break;
default:
AnythingElse();
}
And wrap what you need to do for each of the above in separate methods.
The third method would be my preference here. It's cleaner and easier to debug than using complex mixtures of switch and if.

You could just use if statements instead
var num = 0;
if(num == 1)
{
// do stuff applicable to 1 only
}
else if(num == 2)
{
// do stuff applicable to 2 only
}
else if(num == 3)
{
// do stuff applicable to 3 only
}
if(num == 2 || num == 3)
{
// do stuff applicable to 2 AND 3
}
Or as a switch and an if
switch (num)
{
case 1:
// do stuff applicable to 1 only
break;
case 2:
// do stuff applicable to 2 only
break;
case 3:
// do stuff applicable to 3 only
break;
}
if(num == 2 || num == 3)
{
// do stuff applicable to 2 AND 3
}

You could use the goto case statement and have a unique identifier for combined operations in case 2 and 3. Make sure that that is never hit by any other number:
var num = 0;
var text = "";
switch (num)
{
case 1:
text = "do stuff applicable to 1 only";
break;
case 2:
text = "do stuff applicable to 2 only";
goto case 23;
case 3:
text = "do stuff applicable to 3 only";
goto case 23;
case 23:
text = "do stuff applicable to 2 AND 3";
break;
}
The use of goto is not recommended in general but it is common to use it in switch-statements and situations like that.

Related

Turn if in to switch statement

could I turn this into a switch statement ?
if (donation_euro.Text.Trim().Equals(""))
{
donation_euro.Text = "00.00";
}
if (donation_lui.Text.Trim().Equals(""))
{
donation_lui.Text = "00.00";
}
if (donation.Text.Trim().Equals(""))
{
donation.Text = "00.00";
}
No, because your are not switching on a single variable, but multiple.
I suspect your motivation to do this, is to make the code more readable ? If this is the case, you could put the common logic of your three if's into a method, to reuse the code and better convey the intent.
Not Possible.as switch takes Expression and executes the matching Constant Case Label.
From MSDN :Switch-Case
Each case label specifies a constant value. The switch statement
transfers control to
the switch section whose case label matches
the value of the switch expression
Switch(Expression)
{
case constant1://statements
break;
case constant2://statements
break;
case constant3://statements
break;
}
if you want to switch with single value then it is possible
int a = 3;
if (a == 1)
{
//statements
}
else if(a == 2)
{
//statements
}
else if(a == 3)
{
//statements
}
else if(a == 4)
{
//statements
}
else
{
//statements
}
can be converted into switch as below:
int a = 3;
switch(a)
{
case 1: //statements
break;
case 2: //statements
break;
case 3: //statements
break;
case 4: //statements
break;
default : //statements
break;
}

c# Switch issue. Homework

This is what I have so far. My problem is that none of the cases are responding when you enter either the correct or incorrect answer. I'm not really sure where to go from here. The program asks you answer two random numbers being multiplied. And then it should give you one of the eight responses.
int result = 0;
int caseSwitch = 0;
string question = DoMultiplication(out result);
Console.WriteLine(question);
int answer = Convert.ToInt32(Console.ReadLine());
if (answer == result)
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("Very Good");
break;
case 2:
Console.WriteLine("Excellent");
break;
case 3:
Console.WriteLine("Nice Work");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
}
}
else
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("No, Please Try Again.");
break;
case 2:
Console.WriteLine("Wrong, Try Once More");
break;
case 3:
Console.WriteLine("Don't Give Up!");
break;
case 4:
Console.WriteLine("No, Keep Trying!");
break;
caseSwitch is always 0, so your switch will always fall through without writing anything to console.
If you want a random response you could do something like this:
int result = 0;
int caseSwitch = new Random().Next(1, 4);
string question = DoMultiplication(out result);
Console.WriteLine(question);
int answer = Convert.ToInt32(Console.ReadLine());
if (answer == result)
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("Very Good");
break;
case 2:
Console.WriteLine("Excellent");
break;
case 3:
Console.WriteLine("Nice Work");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
}
}
else
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("No, Please Try Again.");
break;
case 2:
Console.WriteLine("Wrong, Try Once More");
break;
case 3:
Console.WriteLine("Don't Give Up!");
break;
case 4:
Console.WriteLine("No, Keep Trying!");
break;
CaseSwitch is always = 0.
You need to assign a value to it, and-or add a default case to your switch.
You have your int caseSwitch = 0; and I don't see you changing it in your code to any of 1-4. So what do you expect it to do if you dont have the caseSwitch changed...

Finding the index of chars that repeats

I'm really bad at explaining things, but I'll try my best.
I'm making a small program that converts one word into another as you type. Each letter that is typed goes through this section of code where it is changed to a different letter depending on its Index position of the whole word.
My issue here is that when there are repeating letters, the letters that repeat don't change according to their position within the word but rather the first occurrence.
For example this made up word "bacca". If you put that through the code, it SHOULD change to "vrwiy" but instead it changes to "vrwwr". I know why this is too. It's because the switch statement loops through the word that needs to be converted. However I'm without a clue on how to make it change each char according to it's own individual position within the index of the string. I thought maybe the LastIndexOf() method would work but instead it just reverses the order. So if I were to type the letter "a", it would come out as "n", but if I were to type "aa", it would switch the first "a" to "r" because the second is at the IndexOf 1 get's changed to "r".
private void inputTbox_TextChanged(object sender, EventArgs e)
{
List<string> rawZnWordList = new List<string>();
foreach (char a in inputTextBox.Text)
{
switch (inputTextBox.Text.IndexOf(a))
{
case 0:
switch (a)
{
case 'a':
rawZnWordList.Add("n");
continue;
case 'b':
rawZnWordList.Add("v");
continue;
case 'c':
rawZnWordList.Add("a");
continue;
default:
break;
}
continue;
case 1:
switch (a)
{
case 'a':
rawZnWordList.Add("r");
continue;
case 'b':
rawZnWordList.Add("x");
continue;
case 'c':
rawZnWordList.Add("z");
continue;
default:
break;
}
continue;
case 2:
switch (a)
{
case 'a':
rawZnWordList.Add("t");
continue;
case 'b':
rawZnWordList.Add("l");
continue;
case 'c':
rawZnWordList.Add("w");
continue;
default:
continue;
}
continue;
case 3:
switch (a)
{
case 'a':
rawZnWordList.Add("u");
continue;
case 'b':
rawZnWordList.Add("i");
continue;
case 'c':
rawZnWordList.Add("o");
continue;
default:
break;
}
continue;
case 4:
switch (a)
{
case 'a':
rawZnWordList.Add("y");
continue;
case 'b':
rawZnWordList.Add("m");
continue;
case 'c':
rawZnWordList.Add("d");
continue;
default:
break;
}
continue;
default:
break;
}
}
string finalZnWord = string.Join("", rawZnWordList.ToArray());
outputTextBox.Text = finalZnWord;
}
You should try using a for loop instead, like this:
for (int i = 0; i < inputTextBox.Text.Length; i++)
{
char a = inputTextBox.Text[i];
switch (i)
{
case 0:
switch (a)
...
Hope this helps ;).
You need to keep track of the index inside your foreach instead of using .IndexOf. You could also use a regular for loop instead of a foreach but this way is a minimal change to your code.
private void inputTbox_TextChanged(object sender, EventArgs e)
{
List rawZnWordList = new List();
int index = 0;
foreach (char a in inputTextBox.Text)
{
switch (index)
{
case 0:
switch (a)
{
case 'a':
rawZnWordList.Add("n");
continue;
case 'b':
rawZnWordList.Add("v");
continue;
case 'c':
rawZnWordList.Add("a");
continue;
default:
break;
}
continue;
case 1:
switch (a)
{
case 'a':
rawZnWordList.Add("r");
continue;
case 'b':
rawZnWordList.Add("x");
continue;
case 'c':
rawZnWordList.Add("z");
continue;
default:
break;
}
continue;
case 2:
switch (a)
{
case 'a':
rawZnWordList.Add("t");
continue;
case 'b':
rawZnWordList.Add("l");
continue;
case 'c':
rawZnWordList.Add("w");
continue;
default:
continue;
}
continue;
case 3:
switch (a)
{
case 'a':
rawZnWordList.Add("u");
continue;
case 'b':
rawZnWordList.Add("i");
continue;
case 'c':
rawZnWordList.Add("o");
continue;
default:
break;
}
continue;
case 4:
switch (a)
{
case 'a':
rawZnWordList.Add("y");
continue;
case 'b':
rawZnWordList.Add("m");
continue;
case 'c':
rawZnWordList.Add("d");
continue;
default:
break;
}
continue;
default:
break;
}
index++;
}
string finalZnWord = string.Join("", rawZnWordList.ToArray());
outputTextBox.Text = finalZnWord;
}
I think this does the same thing and is a lot more readable. Of course replace the letter rings with your own values. I only went up to 5 characters. I'm guessing you would want more.
//replacement letter rings
char[][] aRep = {
"xfhygaodsekzcpubitlvnjqmrw".ToCharArray(),
"wqtnsepkbalmzyxvordhjgifcu".ToCharArray(),
"nyxgmcibplovkwrszaehftqjud".ToCharArray(),
"soqjhpybuwfxvartkzginemdcl".ToCharArray(),
"pldquhegkaomcnjrfxiysvtbwz".ToCharArray(),
};
private string newText(string inVal)
{
char[] ia = inVal.ToCharArray(); //in array
int l = ia.Length;
char[] oa = new char[l]; //out array
for (int i = 0; i < l; i++)
oa[i] = aRep[i][(int)ia[i]-97]; //lowercase starts at char97
return new string(oa);
}
Here is also the code I used to generate the rings:
//generate random letter rings
//char[] ascii = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
//for (int i = 0; i < 8; i++)
// new string(ascii.OrderBy (x => Guid.NewGuid() ).ToArray()).Dump();
I did some very simple testing and this seemed quite a bit faster than the original approach and more importantly (to me) it is way more readable and a lot easier to see your replacement letter sequences. I think there is some more optimization to be done, but this i think is a good start. Just call this with your text during 'on change'.

Add a additional condition to Case Statement in Switch

Is it possible to add a additional Condition to Switch Statement like below in C#
switch(MyEnum)
{
case 1:
case 2:
case 3 && Year > 2012://Additional Condtion Here
//Do Something here..........
break;
case 4:
case 5:
//Do Something here..........
break;
}
In above mentioned example if MyEnum = 3 then it has to be excuted if Year > 2012... Is it possible?
[EDITED]
Year > 2012 is not applicable to case 1 & case 2.
C#7 new feature:
case...when
https://learn.microsoft.com/en-us/dotnet/articles/csharp/whats-new/csharp-7
public static int DiceSum4(IEnumerable<object> values)
{
var sum = 0;
foreach (var item in values)
{
switch (item)
{
case 0:
break;
case int val:
sum += val;
break;
case IEnumerable<object> subList when subList.Any():
sum += DiceSum4(subList);
break;
case IEnumerable<object> subList:
break;
case null:
break;
default:
throw new InvalidOperationException("unknown item type");
}
}
return sum;
}
In order for it to work the way you've indicated with the fallthrough logic for 1 and 2, I'd suggest moving the //do something here portion out to a method or function and then doing this:
case 1:
case 2:
DoSomething();
break;
case 3:
if(Year > 2012) { DoSomething(); }
break;
The other alternative would be:
case 1:
case 2:
case 3:
if (MyEnum != 3 || Year > 2012) {
// Do something here
}
break;
but I think the first option is much more intuitive and readable.
The answer is no.
You'll need the following:
switch (MyEnum)
{
case 1:
case 2:
DoSomething();
break;
case 3:
if (Year > 2012) DoSomething();
break;
}
You can't add condition to a case. Case clause has to be a compile time constant. Instead you can use an if statement inside the case statement.
case 3:
if( > 2012)
{
//Do Something here..........
}
break;
You have to use the if condition inside your case , you can't use && in case statement, use like below:
switch(MyEnum)
{
case 1:
case 2:
case 3: //Additional Condtion Here
if (Year > 2012)
{
//Do Something here..........
}
break;
case 4:
case 5:
//Do Something here..........
break;
}
Or, alternatively, you can add the condition to the switch:
switch (MyEnum!=3 || Year>2012 ? MyEnum : -1)
{
case 1:
case 2:
case 3:
//Do Something here..........
break;
case 4:
case 5:
//Do Something here..........
break;
}
Most of the time, I do something like that...
(sorry for the naming, the use case didn't inspire me)
Considering those private classes:
private class NumberState
{
public static NumberState GetState(int number, int year)
{
if (number == 1)
return new FirstNumberState();
if (number == 2)
return new FirstNumberState();
if (number == 3 && year > 2012)
return new FirstNumberState();
if (number == 4)
return new SecondNumberState();
if (number == 5)
return new SecondNumberState();
return new DefaultNumberState();
}
}
private class FirstNumberState : NumberState { }
private class SecondNumberState : NumberState { }
private class DefaultNumberState : NumberState { }
Then you can do:
switch (NumberState.GetState(MyEnum, Year))
{
case FirstNumberState _:
// do something
break;
case SecondNumberState _:
// do something
break;
case DefaultNumberState _:
default:
throw new Exception("Unhandled number state");
}
It's easy to read even when your conditions get more complicated.
You can use C# 8 feature
public static bool SomeHelper(int value)
=> value switch
{
100 => true,
var x when x >= 200 && x <= 300 => true,
_ => false, // All other values
};
You will have true with values 100, 200...300 and false with other values
Also you can use params:
public static bool SomeHelper(int value, bool param)
=> value switch
{
100 => true,
var x when x >= 200 && x <= 300 && param => true,
_ => false, // All other values
};
in this case you will have true only if value is 100 and param is false

How add "or" in switch statements?

This is what I want to do:
switch(myvar)
{
case: 2 or 5:
...
break;
case: 7 or 12:
...
break;
...
}
I tried with "case: 2 || 5" ,but it didn't work.
The purpose is to not write same code for different values.
By stacking each switch case, you achieve the OR condition.
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
You do it by stacking case labels:
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
You may do this as of C# 9.0:
switch(myvar)
{
case 2 or 5:
// ...
break;
case 7 or 12:
// ...
break;
// ...
}
case 2:
case 5:
do something
break;
Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write
switch(myvar)
{
case 2:
case 5:
{
//your code
break;
}
// etc...
}
The example for switch statement shows that you can't stack non-empty cases, but should use gotos:
// statements_switch.cs
using System;
class SwitchTest
{
public static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = 0;
switch(n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or3.");
break;
}
if (cost != 0)
Console.WriteLine("Please insert {0} cents.", cost);
Console.WriteLine("Thank you for your business.");
}
}
Since C# 8 there are switch expressions that are better readable: no case, : and break;/return needed anymore. Combined with C# 9's logical patterns:
static string GetCalendarSeason(DateTime date) => date.Month switch
{
3 or 4 or 5 => "spring",
6 or 7 or 8 => "summer",
9 or 10 or 11 => "autumn",
12 or 1 or 2 => "winter",
_ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};
Limitation: with this syntax, at the right of the => you cannot use curly braces ({ and }) for statements.

Categories

Resources