Consider following case statement
Case 'A':
break;
Case 'B':
Case 'C':
// some logic
int i = 0;
// here I need i =5 (if case id 'B') and i=10 (if case is 'C')
// Rest of the logic is same
break;
I know I can achieve this by writing seperate case for 'B' and 'C' and writing rest of the logic in a seperate function and call that function in 'B' and 'C' case.
But is there any way, I can check the case in Case statement only ... as follows
Case 'B':
Case 'C':
// Can I check here
// if (case == 'B')
// i = 5;
// if (case == 'C')
// i = 10;
// Rest of the logic
I tried the following which worked without any problems:
switch (a)
{
case 'A':
Console.WriteLine("Es ist ein 'A'.");
break;
case 'B':
case 'C':
if (a == 'B')
Console.WriteLine("Es ist ein 'B'.");
if (a == 'C')
Console.WriteLine("Es ist ein 'C'.");
break;
}
But if you're just checking if it's 'B' or 'C', I would suggest writing two separate cases.
Put your //Rest of Logic inside a new method, and do separate test cases for a neater code:
private void DoSomething(int i)
{
//Rest of Logic
}
public void SwitchMethod(char input)
{
int i = 0;
Switch (input)
{
case 'A':
break;
case 'B':
i = 5;
DoSomething(i);
break;
case 'C':
i = 10;
DoSomething(i);
break;
}
}
Related
I was wondering if I can use a switch with multiple expressions. For example:
string s = "A";
int i = 3;
switch (s, i)
{
case "A", 1:
//DoStuff
break;
case "A", 2:
//DoStuff
break;
case "A", 3:
//DoStuff
break;
...
}
I don't want to use hundreds of if(s == "A" && i == 1)-Statements so it would be great if there's a better solution.
PS: This switch is just an example, I'm actually using it with more complex strings like Names
You certainly can, for example by using tuples:
string s = "A";
int i = 3;
switch (s, i)
{
case ("A", 1):
// DoStuff.
break;
case ("A", 2):
// DoStuff.
break;
case ("A", 3):
// DoStuff.
break;
}
(Basically exactly what you typed, except with the addition of parenthesis in the cases to make them into tuples.)
Note that this requires C# 7 or later.
Since C# 7, it is possible to do the following:
string s = "A";
int i = 3;
switch (s)
{
case "A" when i == 1:
//DoStuff
break;
case "A" when i == 2:
//DoStuff
break;
case "A" when i == 3:
//DoStuff
break;
...
}
Problem: How to write this if-codeblock into a switch case? I have only a problem with the boolean.
int Note = 0;
Console.WriteLine("What is your note?: ");
Note = Convert.ToInt32(Console.ReadLine());
if ((Note < 1) || (Note > 6))
{
Console.WriteLine("Your input is wrong!");
}
else
{
if (Note <= 4)
{
Console.WriteLine("Passed");
}
else
{
Console.WriteLine("Failed");
}
}
I tried to write this codeblock into a switch-method.
int Note = 0;
Console.WriteLine("What ist your note?: ");
Note = Convert.ToInt32(Console.ReadLine());
switch (Note)
{
case Note < 1 || Note > 6:
Console.WriteLine("Your input is wrong!");
break;
case Note <= 4:
Console.WriteLine("Passed");
break;
}
Error Message: I can't convert the string into int.
C#7+ supports range-based switching:
switch (Note)
{
case int n when n< 1 || Note > 6:
Console.WriteLine("Your input is wrong!");
break;
case int n when n <= 4:
Console.WriteLine("Passed");
break;
}
You can do it like that if you really need a switch
switch (Note)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine("Passed");
break;
case 5:
case 6:
Console.WriteLine("Failed");
break;
default:
Console.WriteLine("Your input is wrong!");
break;
}
This is not where switch statements are for. You should keep using if.
I will proof that very easily, using a switch, as you asked:
switch (Note)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine("Passed");
break;
case 5:
case 6:
Console.WriteLine("Failed");
break;
default:
Console.WriteLine("Your input is wrong!");
break;
}
This is just way too verbatim. You don't want to write down every value. if is more appropriate.
I'm working a little with switch statements and want to know how to ignore the case sensitivity when it comes to input values.
Here is my code:
using System;
namespace SwitchStatements
{
class MainClass
{
public static void Main(string[] args)
{
Start:
Console.WriteLine("Please Input the Grade");
char grade = Convert.ToChar(Console.ReadLine());
switch (grade)
{
case 'A':
Console.WriteLine("Excellent Work!");
break;
case 'B':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
break;
}
Console.ReadKey();
goto Start;
}
}
}
If I put 'a' in instead of 'A' it returns the default response.
Can I use perhaps a .Comparison of some sort? If so where would I put it?
You can use ConsoleKey as condition for switch, the code will be like the following.
var grade =Console.ReadKey().Key;
switch (grade)
{
case ConsoleKey.A:
Console.WriteLine("Excellent Work!");
break;
case ConsoleKey.B:
// Something here
break;
case ConsoleKey.C:
// Something here
break;
case ConsoleKey.D:
// Something here
break;
case ConsoleKey.E:
// Something here
break;
default:
// Something here
break;
}
So that you can avoid converting the input to uppercase/Lower case, and then it goes for another conversion To Char. Simply use ConsoleKey Enumeration inside the switch.
You can use ToUpper(); Like
Convert.ToChar(Console.ReadLine().ToUpper());
and to get saved from the error of getting more charaters with Console.ReadLine() you can use
char grd = Convert.ToChar(Console.ReadKey().KeyChar.ToString().ToUpper());
you can use like following also
char grade = Convert.ToChar(Console.ReadLine().ToUpperInvariant());
https://msdn.microsoft.com/en-us/library/system.string.toupperinvariant.aspx
Convert to uppercase before switch like below,
grade = Char.ToUpper(grade);
Change
char grade = Convert.ToChar(Console.ReadLine());
To
char grade = Convert.ToChar(Console.ReadLine().ToUpper());
https://msdn.microsoft.com/en-us/library/system.string.toupper(v=vs.110).aspx
Write Switch on grade.ToUpper() like this and don't change change it's value, may be you will need it after
char grade = Convert.ToChar(Console.ReadLine());
switch (grade.ToUpper())
{
case 'A':
Console.WriteLine("Excellent Work!");
break;
case 'B':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
break;
}
You may fall from one case to another like this
public static void Main(string[] args)
{
Boolean validInputRead = false;
Char grade;
while(!validInputRead)
{
validInputRead = true;
Console.WriteLine("Please Input the Grade");
grade = Convert.ToChar(Console.Read());
switch (grade)
{
case 'A':
case 'a':
Console.WriteLine("Excellent Work!");
break;
case 'B':
case 'b':
Console.WriteLine("Very Good Effort! Just a couple of Errors =)");
break;
case 'C':
case 'c':
Console.WriteLine("You Passed. Push Yourself Next Time");
break;
case 'D':
case 'd':
Console.WriteLine("Better put in more effort next time. I know you can do better");
break;
default:
Console.WriteLine("Invalid Grade.");
validInputRead = false;
break;
}
Console.ReadKey();
}
}
EDIT
Changed from Console.ReadLine() to Console.Read() as suggested
Added while(!validInputRead) as requested
string letterGrade;
int grade = 0;
// This will hold the final letter grade
Console.Write("Input the grade :");
switch (grade)
{
case 1:
// 90-100 is an A
letterGrade = "A";
Console.WriteLine("grade b/n 90-100");
break;
case 2:
// 80-89 is a B
letterGrade = "B";
Console.WriteLine("grade b/n 80-89");
break;
case 3:
// 70-79 is a C
letterGrade = "C";
Console.WriteLine("grade b/n 70-79");
break;
case 4:
// 60-69 is a D
letterGrade = "D";
Console.WriteLine(" grade b/n 60-69 ");
break;
default:
// point whic is less than 59
Console.WriteLine("Invalid grade");
break;
}
i have problems when adding mullti values into same case:
this is my c# code
string input = combobox1.selectedvalue.ToString();
switch(input)
{
case "one";
return 1;
break;
case "two";
return 2;
break;
case "three" , "four": // error here
return 34;
break;
default:
return 0;
}
need your help for
Just use separate labels:
string input = combobox1.selectedvalue.ToString();
switch(input)
{
case "one":
return 1;
break;
case "two":
return 2;
break;
case "three":
case "four":
return 34;
break;
default:
return 0;
}
See switch:
Each switch section contains one or more case labels followed by one or more statements
You can you the fall though, read this for more information
so it's look like this
switch(input)
{
case "one":
return 1;
break;
case "two":
return 2;
break;
case "three":
case "four":
return 34;
break;
default:
return 0;
}
Right syntax is
case "three":
case "four":
return 34;
break;
instead
case "three" , "four":
return 34;
break;
From switch (C# Reference)
A switch statement includes one or more switch sections. Each switch
section contains one or more case labels followed by one or more
statements.
I am developing a console application, that should listen for digits from a numpad keyboard in both num lock states - on and off. The application is running on Raspberry Pi with Arch Linux and Mono. Since I did not found a way, that is compiling under Mono, to permanently turn numlock on, I am using the following method to convert num pad commands to digits:
private string ReadNumPadSymbol(ConsoleKeyInfo keyInfo)
{
char editedSymbol;
switch (keyInfo.Key)
{
case ConsoleKey.Insert:
editedSymbol = '0';
break;
case ConsoleKey.End:
editedSymbol = '1';
break;
case ConsoleKey.DownArrow:
editedSymbol = '2';
break;
case ConsoleKey.PageDown:
editedSymbol = '3';
break;
case ConsoleKey.LeftArrow:
editedSymbol = '4';
break;
case ConsoleKey.Clear:
editedSymbol = '5';
break;
case ConsoleKey.RightArrow:
editedSymbol = '6';
break;
case ConsoleKey.Home:
editedSymbol = '7';
break;
case ConsoleKey.UpArrow:
editedSymbol = '8';
break;
case ConsoleKey.PageUp:
editedSymbol = '9';
break;
default:
return String.Empty;
}
return editedSymbol.ToString();
}
It works as expected under Windows, but under Linux, the method returns empty string, when the "5" button is pressed. For some reason it does not enters the ConsoleKey.Clear case. Is there a fix for this?
Thanks!