switch(number){
case 2:
a+=b;
break;
case 3:
a+=b;
break;
case 4:
a+=b;
d=f;
break;
case 5:
d=e;
break;
}
how to minimize first three switch cases which which does similar work?
If you using C# 7, you can make use of Pattern Matching, even though this is an overkill as rightly pointed by Jon Skeet. But in case, you want to stick to switch case, and want to reduce 'case', you could do the following
switch(number)
{
case var _ when number == 2 || number==3 || number==4:
a+=b;
if(number ==4)
d=f
break;
case 5:
d=e;
break;
}
You can also replace the first case with variants like
case var _ when new[]{2,3,4}.Contains(number):
Or
case var _ when number >= 2 || number <= 3: // As pointed by earlier answer
Without pattern matching, you could do the following as well
switch(number)
{
case 2:
case 3:
case 4:
a+=b;
if(number ==4)
d=f;
break;
case 5:
d = e;
break;
}
Btw, if your problem is "a+b" is about 60 lines of code, you always have the option to make it a function (and move it out of switch case) to increase its readability.
switch(number)
{
case 2:
case 3:
case 4:
MethodAbAction();
if(number ==4)
MethodDFAction();
break;
case 5:
MethodDEAction();
break;
}
btw, a 60 line method is never fun to read. It would be better if you can split up.
if (2 <= number && number <= 4) {
a += b;
}
if (number == 4) {
d = f;
} else if (number == 5) {
d = e;
}
if (number != 5)
{
a += b;
}
if (number == 4)
{
d = f;
}
else
if (number == 5)
{
d = e;
}
Related
I want to write a code in C# that asks a user to input 2 numbers to compare which is higher but cant seem to get an output from this.
{
class Program
{
public static int Max { get; private set; }
static void Main(string[] args)
{
Console.WriteLine("Please enter 2 (two) integer numbers on a separate line: ");
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
switch (Max)
{
case 1:
if (num1 < num2)
{
Console.WriteLine(num2 + "is Maximum");
}
break;
case 2:
if (num1 > num2)
{
Console.WriteLine(num1 + "is Maximum");
}
break;
}
}
}
}
You are using the "Max" variable on the condition of the switch, but you never actually declare "Max", and the switch is only expectating the numbers 1 or 2, because you put case 1: and case 2:
So the correct way to show output is this:
if(num1 > num2)
{
Max = 1;
}
else
{
Max = 2;
}
switch(Max)
{
case 1:
Console.WriteLine(num1 + "is Maximum");
break;
case 2:
Console.WriteLine(num2 + "is Maximum");
break;
}
This is just in case you need to use a switch case, because you can do it only with a simple if
case cannot be used to compare values of two numbers you might just want to use if-else statement or if you just want a application of case statement use this :
switch (input)
{
case 1:
Console.WriteLine("a");
break;
case 2:
Console.WriteLine("b");
break;
case 3:
Console.WriteLine("c");
break;
case 4:
Console.WriteLine("d");
break;
case 5:
Console.WriteLine("e");
break;
case 6:
Console.WriteLine("f");
break;
case 7:
Console.WriteLine("g");
break;
default:
Console.WriteLine("Invalid input");
break;
}
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.
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;
}
}
when i tried to use the Switch case function, it goes always to the default message besides case 5:
private void btnCandlesLight_Click(object sender, EventArgs e)
{
int result;
result = Convert.ToInt32(textBox1.Text);
switch(result)
{
case 1:
day1.Start();
candlesOne();
break;
case 2:
day2.Start();
candlesTwo();
break;
case 3:
day3.Start();
candlesThree();
break;
case 4:
day4.Start();
candlesFour();
break;
case 5:
day5.Start();
candlesFive();
break;
case 6:
day6.Start();
candlesSix();
break;
case 7:
day7.Start();
candlesSeven();
break;
case 8:
day8.Start();
candlesEight();
break;
default:
MessageBox.Show("Enter new day");
break;
}
}
When I Enter the value 1 for example to the text box, the default case works, but only when I enter the value 5 it works perfectly.
If you want to see the difference between the function "candlesOne" to "candlesFive":
The "c" variable is a variable of the seconds. i tried to use a timer in a way of lighting up the candles every 2-3 seconds.
public void candlesOne()
{
firedmatch.Left = firedmatch.Left + 100;
if (c == 1)
{
candle1.Visible = true;
}
if (c == 3)
{
candle2.Visible = true;
}
}
and:
public void candlesFive()
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3)
{
candle2.Visible = true;
}
if(c == 5)
{
candle3.Visible = true;
}
if(c == 7)
{
candle4.Visible = true;
}
if(c == 11)
{
candle5.Visible = true;
}
}
I haven't found a mistake,
can you guys help me?
Thanks
Have you checked if you really get for example (int)1 as a result of the "1" input from your conversion?
On a broader scale, there is a lot of repetition in your code, you should consider refactoring it a little.
In your CandlesOne and CandlesFive methods, you use a c variable, no idea what that is or where it comes from. Those two methods (and probably the other CandlesXXX() do the same kind of things. Can't you remove complexity by generalizing the logic? Can the result used in your switch-case be passed as a parameter and used to trigger the numbers of c == X calls in the CandleXXX() methods?
This way you could remove the switch and lose a lot of complexity!
Edit
If you have further problems, consider creating a .NET Fiddle, I miss a lot of context in your code so I cannot efficiently help you here.
Some refactoring ideas for you:
// Somewhere else in your code, create a dictionary with your day1-day8 objects
var days = new Dictionary<int, Day>()
days[1] = day1;
...
days[8] = day8;
//Simplfiy your method
private void btnCandlesLight_Click(object sender, EventArgs e)
{
try
{
var dayIndex = Convert.ToInt32(textBox1.Text);
if(dayIndex > 0 && dayIndex <= 8)
{
days[dayIndex].Start(); //Get the corresponding day via its Key
LightUpCandles(dayIndex); //pass the key as a parameter
}
else
{
MessageBox.Show("Enter new day");
}
}
catch(InvalidCastException exception)
{
//Whatever you do when the textbox cannot be parsed
}
}
I still don't get what your candlesOne to five methods are really doing or why the method "candlesOne" lights up two candles (pay attention to the variable naming). I also don't get how this makes up some kind of timer... but here's a first potential refactoring for it anyway:
public void LightUpCandles(int dayIndex)
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3 && dayIndex > 1)
{
candle2.Visible = true;
}
if(c == 5 && dayIndex > 2)
{
candle3.Visible = true;
}
if(c == 7 && dayIndex > 3)
{
candle4.Visible = true;
}
if(c == 11 && dayIndex > 4)
{
candle5.Visible = true;
}
}
Your switch logic is correct which I tested with the following;
int result;
result = Convert.ToInt32(textBox1.Text);
switch (result)
{
case 1:
MessageBox.Show("1");
break;
case 2:
MessageBox.Show("2");
break;
case 3:
MessageBox.Show("3");
break;
case 4:
MessageBox.Show("4");
break;
case 5:
MessageBox.Show("5");
break;
case 6:
MessageBox.Show("6");
break;
case 7:
MessageBox.Show("7");
break;
case 8:
MessageBox.Show("8");
break;
default:
MessageBox.Show("Enter new day");
break;
}
If you don't get the same results I would perhaps look at making the message boxes above display the data type of the variable.
MessageBox.Show(result.GetType().ToString());