IF and ELSE statement issue - c#

apologies for the vague title, I'm having a few issues with if statements in my program, this is not the exact code but should still outline my issues, in my program I have this:
if(entry.Contains("a"))
{
Console.WriteLine("a");
}
if(entry.Contains("b"))
{
Console.WriteLine("b");
}
if(entry.Contains("c"))
{
Console.WriteLine("c");
}
else
{
Console.WriteLine("d");
}
So my issue is, if I was to type a or b(the first two if statements), the else statement would still occur but if I was to type c, the else statement would not occur but I want it to act so that if i type a, b or c the else statement would not occur.
Any help would be much appreciated.

You want
if(entry.Contains("a"))
{
Console.WriteLine("a");
}
else if(entry.Contains("b"))
{
Console.WriteLine("b");
}
else if(entry.Contains("c"))
{
Console.WriteLine("c");
}
else
{
Console.WriteLine("d");
}
Additionally, if you are using all the same variable types (i.e. string or int) you can also use a case statement. It does the exact same thing, it's just a bit neater:
switch(stringName)
{
case "a":
Console.Writeline("a");
break;
case "b":
Console.Writeline("b");
break;
case "c":
Console.Writeline("c");
break;
case "d":
Console.Writeline("d");
break;
default:
Console.Writeline("none of the above");
break;
}
I don't think it'll work with entry.Contains() though.

Related

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.

Multiple if vs else if which is faster

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.

C# How do I make a switch ignore invalid input?

I am trying to make a simple console game that starts with a title screen. The user inputs 'N' for a new game, 'L' to load a game, or 'E' to exit. I have this set up as a switch, but I need to know how to make the program ignore any input other than the aforementioned keys. I've Googled this question but didn't find an answer. Please help if you can.
I don't see much point in posting the code as 10 lines of a simple switch probably wouldn't be terribly helpful to solving the problem. Also, if there would be an easier / more efficient way than a switch, I would love to know.
Thanks.
You can use a default: statement to handle the other (unknown) cases:
switch(inputString.ToLower())
{
case "n":
// Handle new
break;
//.. handle known cases
default:
Console.WriteLine("Unknown option chosen. Please enter valid option:");
// Re-read values, etc?
break;
}
Anything not specified in one of your other cases will fall into the default case, which you can then use to prompt for valid input.
If you want to actually ignore all keys other than valid ones you could do something like this:
public static char ReadKey(IEnumerable<char> validKeys)
{
var validKeySet = new HashSet<char>(validKeys);
while (true)
{
var key = Console.ReadKey(true);
if (validKeySet.Contains(key.KeyChar))
{
//you could print it out if you wanted.
//Console.Write(key.KeyChar);
return key.KeyChar;
}
else
{
//you could print an error message here if you wanted.
}
}
}
When you use ReadKey(true) the true indicated that it will intercept that key and not display it on the console. This gives you the option of determining if it's valid or invalid.
If a switch statement does not have a default block, and if the expression being switched on does not match any of the case blocks, the switch statement does nothing.
When you have only 3 cases, a switch isn't much more efficient than just a simple if-else construct.
if (input == "N")
{
// New game
}
else if (input == "L")
{
// Load game
}
else if (input == "E")
{
// Exit game
}
// if none of the cases match, the input is effectively ignored.
If you insist on using a switch, then your construct is very similar:
switch (input)
{
case "N":
//New Game
break;
case "L":
//Load Game
break;
case "E":
//Exit Game
break;
default:
//Do nothing (ignore unmatched inputs)
break;
}
Thanks for the replies, guys. I managed to solve the problem by doing the following:
static void titleInput()
{
ConsoleKeyInfo titleOption = Console.ReadKey(true);
switch (titleOption.Key)
{
case ConsoleKey.N:
Console.Clear();
break;
case ConsoleKey.L:
break;
case ConsoleKey.E:
Environment.Exit(0);
break;
default:
titleInput();
break;
}
}
I'm not sure how 'proper' this is, but it does what I need it to do. Any keys other than 'N', 'L', and 'E' no longer do anything.

switch and if in C#

Why does the following work (compile):
public void SaveCurrentTab(string currentTabIndex)
{
if (currentTabIndex == MainInfoPnl.ClientID)
PartialSave1();
else if (currentTabIndex == ContactInfoPnl.ClientID)
PartialSave2();
else if (currentTabIndex == BankInfoPnl.ClientID)
PartialSave3();
else if (currentTabIndex == ServicesPnl.ClientID)
PartialSave4();
else if (currentTabIndex == AttachmentsPnl.ClientID)
PartialSave5();
}
But, the following does not?
public void SaveCurrentTab(string currentTabIndex)
{
switch (currentTabIndex)
{
case MainInfoPnl.ClientID:
PartialSave1();
break;
case ContactInfoPnl.ClientID:
PartialSave2();
break;
case BankInfoPnl.ClientID:
PartialSave3();
break;
case ServicesPnl.ClientID:
PartialSave4();
break;
case AttachmentsPnl.ClientID:
PartialSave5();
break;
}
}
Presumably because MainInfoPnl.ClientID isn't a compile-time constant. It may be public static readonly for example, which isn't the same as const. If that doesn't help, show us more about the code and the error message you're getting.
The case statements must be constant strings for a switch - an if condition has no such restriction.
A switch in C# only works with constant values. For values determined at runtime, use a if-else construction.
Try this:
public void SaveCurrentTab(string currentTabIndex)
{
switch (Convert.ToInt32(currentTabIndex))
{
case (int)MainInfoPnl.ClientID:
PartialSave1();
break;
case (int)ContactInfoPnl.ClientID:
PartialSave2();
break;
case (int)BankInfoPnl.ClientID:
PartialSave3();
break;
case (int)ServicesPnl.ClientID:
PartialSave4();
break;
case (int)AttachmentsPnl.ClientID:
PartialSave5();
break;
}
}

Using the switch statement in a Windows Forms application

And I'm doing some exercises about switch. I just did it from console application and I would like to do it in window forms applications. I'm looking for syntax on how to do switch in window forms.
In console it's usually like this:
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered numbered two");
break;
default:
break;
how can I do this in my window forms, if I would like to display this cases in listbox1?
Thanks
=======
Thank you. I tried this one but I'm getting an error. This is what I've tried:
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listbox.Items.Add("You have entered number one");
break;
}
}
========
This is the code I'm trying to do:
private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
}
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
this.listBox1.Items.Add("You have entered numbered one");
break;
}
}
====
This is the new code:
private void btnOk_Click(object sender, EventArgs e)
{
string strUserInputNumber;
strUserInputNumber = textBox1.Text.Trim();
Int32 intNumber;
if (Int32.TryParse(textBox1.Text, out intNumber))
{
listBox1.Items.Add(intNumber.ToString());
WriteNumber(intNumber);
}
else
{
MessageBox.Show("Please enter an integer not a character");
}
}
public void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listBox2.Items.Add("You have entered numbered one");
break;
case 2:
listBox2.Items.Add("You have entered numbered two");
break;
case 3:
listBox2.Items.Add("You have entered numbered three");
break;
default:
listBox2.Items.Add("You have exceeded the range of 1-3. Please enter the number between 1-3");
break;
}
The switch/case syntax is identical between WinForms and a console app (or any other type of application or class library), the only difference is how you display the data. If you want to add a string to a listbox (which is apparently what you're asking), it's as simple as
listBox1.Items.Add("Here is the text of the list box item");
This should work:
public void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
listbox.Items.Add("You have entered number one"); break;
}
}
You need to remove the static keyword to get access to the listbox, which is an instance variable.
This works fine:
switch (wordValue)
{
case 1:
this.listBox1.Items.Add("You have entered numbered two");
break;
default:
break;
}

Categories

Resources