Multiple if vs else if which is faster - c#

I'm trying to make a test which is faster in code executing.
Situation 1
int a=2;
if(a==1)
{
//code here
}
if(a==2)
{
//code here
}
if(a==3)
{
//code here
}
Situation 2
int a=2;
if(a==1)
{
//code here
}
else if(a==2)
{
//code here
}
else if(a==3)
{
//code here
}
In situation 1, 'int a' is always different value inside if statements

If you have a lot of if or if else statements I would recommend a switch statement like this:
int a = 2;
switch (a)
{
case 1:
break;
case 2:
break;
case 3:
break;
}
Reference: http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

The second code block can be faster because the first one always tests every condition. The second one stops testing after it finds a match.

Related

Trying to create a switch-case menu

So I'm working on a Switch-Case menu for my program but I'm having multiple issues (I'm probably missing something real obvious here)
So first off I'm trying to implement a while loop to make it possible to return to the menu after executing any of the case methods. However when trying to implement a while loop it doesn't seem to recognise my bool variable for some reason.
Secondly I'm not quite sure how to make it so the user can return to the start menu after they've done what they want to do in the case they've chosen, this probably has a real easy solution, but I just can't find one.
[code]
private string[] säten = new string[24];
private int Antal_passagerare = 0;
public void Run()
{
bool continue = true;
while(continue)
{
string menu = (Console.ReadLine());
int tal = Convert.ToInt32(menu);
switch(tal)
{
case 1:
Add_passagerare;
break;
case 2:
break;
case 3:
break;
}
}
}
[/code]
Your problem is that your local variable name conflicts with the C# keyword (or statement) continue which controls the flow of a loop (e.g. for, foreach, while, etc). Another control flow keyword is break.
You must rename the local variable. But because of the flow control keywords you can drop the local variable (see below). Also use Int32.TryParse to avoid your program from crashing, if the user inputs a non numeric value. In this context you can see the statements continue and break at work:
// Start an infinite loop. Use the break statement to leave it.
while (true)
{
string userInput = Console.ReadLine();
// Quit if user pressed 'q' or 'Q'
if (userInput.Equals("Q", StringComparison.OrdinalIgnoreCase)
{
// Leave the infinite loop
break;
}
// Check if input is valid e.g. numeric.
// If not show message and ask for new input
if (!(int.TryParse(userInput, out int numericInput))
{
Console.WriteLine("Only numbers allowed. Press 'q' to exit.");
// Skip remaining loop and continue from the beginning (ask for input)
continue;
}
switch (numericInput)
{
case 1:
break;
case 2:
Add_passagerare();
break;
case 3:
break;
}
}

Using switch case with thread safe enum

If I have an Enum as follows:
private object myEnumValLock = new object();
private MyEnum _myEnumVal;
public MyEnum MyEnumVal
{
get
{
lock(this.myEnumValLock)
{
return this._myEnumVal;
}
}
set
{
lock(this.myEnumValLock)
{
if (value != this._myEnumVal)
{
this.HandleNewMyEnumVal(this._myEnumVal, value);
this._myEnumVal = value;
}
}
}
}
When using switch case, can I directly use the property like this:
private void MyFunc()
{
switch (this.MyEnumVal)
{
case MyEnum.First:
// Do Something
break;
case MyEnum.Second:
// Do Something
break;
}
}
Or should I read it first and then use switch on the read value like this:
private void MyFunc()
{
var myEnumVal = this.MyEnumVal;
switch (myEnumVal)
{
case MyEnum.First:
// Do Something
break;
case MyEnum.Second:
// Do Something
break;
}
}
If using if ... else as in this question, I'd need to read the value first. Is it the same case with switch statement? What is the behaviour of the switch statement? Does it read the value at every case statement or reads only once at the beginning?
As #mjwills suggested, I put a breakpoint in the getter and it got hit only once at the beginning of the switch statement. I can't find any specific reference where it says the switch statement reads the value only once (please comment if you find the reference). But the breakpoint does prove it.
So, although you need to have read the value beforehand in case of if ... else, in case of the switch statement, you don't need to.

Is there an easier way of writing several if/else statements into eachother?

I sometimes have myself writing code which requires several layers of if/else statements incorporated into each other (example can be found below).
I was wondering if I could shorten it up a bit, because sometimes I have trees of if/else statements of over 70 lines of code, and they are honestly just filling way too much compared to how many of the lines seem redundant.
Here's an example code:
if (labelGiveTip1.Visible == true)
{
if (labelGiveTip2.Visible == true)
{
labelGiveTip3.Visible = true;
if (labelGiveTip3.Visible == true)
{
Custom_DialogBox.Show("All of your hints for this assignment is used, do you want annother assignmment?", //main text argument
"Error: No more hints", //header argument
"Back", //first button text argument
"Get a new assignment"); //second button text argument
//this is a custom dialog box
result = Custom_DialogBox.result;
switch (result)
{
case DialogResult.Yes:
buttonNextAssignment.PerformClick();
break;
case DialogResult.Cancel:
break;
default:
break;
}
}
}
else
{
labelGiveTip2.Visible = true;
}
}
else
{
labelGiveTip1.Visible = true;
}
In my code I tend to check the false condition first and return ASAP. This approach has helped me over years to reduce deeply nested if else. Other than that try to separate related functionalities in to different methods. The example method provided crams too much of logic into one method. If you have ReSharper, it suggests nice improvements and over a period of time, it becomes a habit.
You may check the negated variant of the condition and use else if conditions to avoid that much nesting. E.g. a simplified version for your code:
if (!labelGiveTip1.Visible)
labelGiveTip1.Visible = true;
else if(!labelGiveTip2.Visible)
labelGiveTip2.Visible = true;
else
{
labelGiveTip3.Visible = true;
Custom_DialogBox.Show("All of your hints for this assignment is used, do you want annother assignmment?", //main text argument
"Error: No more hints", //header argument
"Back", //first button text argument
"Get a new assignment"); //second button text argument
//this is a custom dialog box
result = Custom_DialogBox.result;
switch (result)
{
case DialogResult.Yes:
{
buttonNextAssignment.PerformClick();
break;
}
case DialogResult.Cancel:
{
break;
}
default:
{
break;
}
}
}
It is also unnecessary to write labelGiveTip1.Visible == true or labelGiveTip1.Visible == false when they are already boolean values.

Stop a For Loop and start it at next instance where it stopped

So this loop is my first attempt at changing many things. I'm not sure I'm going about it the right way. This is for a rught/wrong answer game. Each time they answer wrong, the loop is called.
In my head it would go to the if related to numAttempts. So if numAttempts ==4 you would see "Wrong Answer 2 tries left!" But each time until the fifth attempt, when the loop is called it always starts at the top regardless of the numattempts.
To mitigate this I also tried adding numAttempts++ in the message check (wrong) code block.
I like the idea of the four loop, because based on each wrong answer a different image will appear, based on HangmanImage() --not currently defined--
I've tried break and return between the for if statements but it isn't working. Can you help me when the loop is called to start the loop where numAttempts =. EX. start at numAttempts==2? And stop the loop after the specific instance is completed?
I'm new to coding and trying to make it work. I appreciate your Patience if my work is 100% wrong or that I shouldn't have done a four look. reading a book and the web is great, but every now again, especially in the beginning people need guidance. Please take a moment and push me in the right direction.
Thank you for your time.
int numAttempts = (0); // global variable, at the start of the class. This allows the variable to be used anywhere with the current value
int maxAttempts = (5);
static void UpdateImage()
{
for (int numAttempts = 0; numAttempts < 6; numAttempts++)
{
if (numAttempts == (1))
{
MessageBox.Show("Wrong Answer 4 tries left!");
{
// HangmanImage();
}
}
else
if (numAttempts == (2))
{
MessageBox.Show("Wrong Answer 3 tries left!");
{
// HangmanImage();
}
}
else
if (numAttempts == (3))
{
MessageBox.Show("Wrong Answer 2 tries left!");
{
// HangmanImage()
}
}
else
if (numAttempts == (4))
{
MessageBox.Show("Wrong Answer 1 try left!");
{
// HangmanImage()
}
}
else
if (numAttempts == (5))
{
MessageBox.Show("You Lose!");
{
// HangmanImage();
}
}
}
}
Here is a working answer: https://dotnetfiddle.net/Z2BaYs
This is the code. Basically, you use the for loop to keep the game in play until the user either runs out of attempts or answers correctly.
using System;
public class Program
{
public static void Main()
{
var maxAttempts = 5;
var correctAnswer = "Edam";
for(int actualAttempts = 1; actualAttempts <= maxAttempts; ++actualAttempts)
{
Console.WriteLine("What is the only cheese that's made backwards?");
Console.WriteLine("Attempt #" + actualAttempts);
var answer = Console.ReadLine();
if(answer.Equals(correctAnswer))
{
Console.WriteLine("Correct!");
break;
}
switch(actualAttempts)
{
case 1:
Console.WriteLine("Whoa. Nice try.");
break;
case 2:
Console.WriteLine("Nope. Wrong.");
break;
case 3:
Console.WriteLine("Incorrect sir!");
break;
case 4:
Console.WriteLine("Still not the correct answer.");
break;
case 5:
Console.WriteLine("...and your done.");
break;
default :
break;
}
}
}
}
This is some example output/input.
What is the only cheese that's made backwards?
Attempt #1
Cheddar
Whoa. Nice try.
What is the only cheese that's made backwards?
Attempt #2
Mozarella
Nope. Wrong.
What is the only cheese that's made backwards?
Attempt #3
Havarti
Incorrect sir!
What is the only cheese that's made backwards?
Attempt #4
Swiss
Still not the correct answer.
What is the only cheese that's made backwards?
Attempt #5
Edam
Correct!
I can tell that you are doing this for school, so I don't want to give much away. But too your question, you are wanting to keep the same iteration in the loop, if I am understanding you. Just to try and stick to your code, you would need to pass in a variable and return one on the function. Like this
int updateImage(int count)
{
for(count < 6; count++)
{
Do what you need;
}
return count;
}
That way you can pass your iteration in and out of the function. Hope this helps.

Expected result not achieved with java but yes with c#

I have a program meant to simulate some probability problem (A variation of the monty hall problem if your interested).
The code is expected to produce 50% after enough iterations but in java it always comes to 60% (even after 1000000 iterations) while in C# it comes out to the expected 50% is there some thing different I do not know about java's Random maybe?
Here is the code:
import java.util.Random;
public class main {
public static void main(String args[]) {
Random random = new Random();
int gamesPlayed = 0;
int gamesWon = 0;
for (long i = 0; i < 1000l; i++) {
int originalPick = random.nextInt(3);
switch (originalPick) {
case (0): {
// Prize is behind door 1 (0)
// switching will always be available and will always loose
gamesPlayed++;
}
case (1):
case (2): {
int hostPick = random.nextInt(2);
if (hostPick == 0) {
// the host picked the prize and the game is not played
} else {
// The host picked the goat we switch and we win
gamesWon++;
gamesPlayed++;
}
}
}
}
System.out.print("you win "+ ((double)gamesWon / (double)gamesPlayed )* 100d+"% of games");//, gamesWon / gamesPlayed);
}
}
At the very least, you have forgotten to end each case block with a break statement.
So for this:
switch (x)
{
case 0:
// Code here will execute for x==0 only
case 1:
// Code here will execute for x==1, *and* x==0, because there was no break statement
break;
case 2:
// Code here will execute for x==2 only, because the previous case block ended with a break
}
You forgot to put breaks at the end of the case statements, so the case (1) continues to case (3).

Categories

Resources