Change variable within a C# 'switch' statement - c#

For a school assignment I'm supposed to create a menu kind of like an ATM.
My professor gave us this code to use:
string choice = null;
do
{
Console.Write("[O]pen Account [I]nquire [D]eposit [W]ithdraw [Q]uit: ");
choice = Console.ReadLine();
choice = choice.ToUpper();
switch (choice)
{
case "O": // open an account
case "I": // inquire
case "D": // deposit
case "W": // withdraw
default: break;
}
} while (choice != "Q");
Here is what I did:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string choice = null;
string CustomerName;
Console.WriteLine("Welcome to Fantasy Bank");
Console.Write("Please enter your name:");
CustomerName = Console.ReadLine();
do
{
Console.WriteLine("What can I do for you");
Console.Write("[O]pen Account [I]nquire [D]eposit [W]ithdraw [Q]uit: ");
choice = Console.ReadLine();
choice = choice.ToUpper();
double CurrentBalance = 0;
switch (choice)
{
case "O": // open an account
Console.Write("Name of account holder:");
Console.WriteLine(CustomerName);
Console.Write("Initial Deposit:");
CurrentBalance = Convert.ToDouble(Console.ReadLine()); // i get a major error if someone types in a letter instead of a number
Console.Write("You have succesfully opened an account with an initial deposit of ");
Console.Write(CurrentBalance);
Console.WriteLine(" at an imaginary bank. Congratulations");
break;
case "I": // inquire
Console.Write(CustomerName);
Console.WriteLine("'s Bank Account");
Console.WriteLine(CurrentBalance);
break;
I did a little bit more, but the problem starts here in case "I". CustomerName is getting replaced by what the user types, like it's supposed to be. But CurrentBalance does not change, and I have to set it equal to something otherwise I get an error.
I start to get the feeling that it may be impossible to change a switch variable inside a switch. I looked in my book for passing references/values, but it doesn't include switch in that section.
If y'all could give me a hint what I'm doing wrong or could show me what could fix my problem, that would be great. I'm not expecting code from you, just a little push in the right direction.

Your problem is the placement of your declaration of CurrentBalance.
Currently you have this:
do
{
double CurrentBalance = 0;
switch (choice) {
/* the rest of your code */
}
}
Should be
double CurrentBalance = 0;
do
{
switch (choice) {
/* the rest of your code */
}
}
Now, the next iteration of your do loop does not reset CurrentBalance to 0

Every iteration of the loop you reset CurrentBalance to 0. Move the line double CurrentBalance = 0; :
string choice;
string CurrentName;
double CurrentBalance = 0;
// ...
do
{
// ...
//double CurrentBalance = 0; NOT HERE
switch( ... )
{
}
}

You should initialize all your variables before going into the loop, not in the loop, or else the variable is re-initialized (cleared to 0) every iteration.
double CurrentBalance = 0;
// other code...
do { // ...
I should mention it doesn't have anything to do with changing variables within a switch. Changing variables within a switch is perfectly permissible.

Related

Editing users info with struct

struct person
{
public int id;
public long phone;
public string name, family, add;
public void Show()
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", id, name, family, phone, add);
}
}
class Program
{
static List<person> info = new List<person>();
static void Edit()
{
Display();
Console.Write("Choose your target ID:");
int ed = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < info.Count; i++)
{
if (ed == info[i].id)
{
Console.WriteLine("1.ID\n2.Name\n3.FamilyName\n4.PhoneNumber\n5.Address\n6.Exit to menu");
Console.WriteLine("Which part of the user info would you like to update:");
int ed1 = Convert.ToInt32(Console.ReadLine());
bool exm = false;
while (true)
{
switch (ed1)
{
case 1:
break;
case 2:
Console.Write("Enter Your Name:");
info[i].name = Console.ReadLine();
break;
case 3:
Console.Write("Enter Your FamilyName:");
info[i].family = Console.ReadLine();
break;
case 4:
Console.Write("Enter Your Name:");
info[i].phone = Convert.ToInt64(Console.ReadLine());
break;
case 5:
Console.Write("Enter Your Name:");
info[i].add =Console.ReadLine();
break;
case 6:
if (exm == true)
Main();
break;
default:
Console.WriteLine("Invalid Operation");
break;
}
}
}
}
}
I'm trying to make a program that gets users info then shows them what they can do. The program methods include input, display, search, remove, edit, all work fine but edit. I don't know how to make it work.
For edit I'm gonna get user id, then let him choose which part of that id he wants to change. In all cases I tried to replace new info but it shows me an error on info[i].would you help me to do this in this way?
You cannot change a property of a struct stored in a list; either change your struct to a class and you will then be able to modify individual properties, or change your editing routine so that it either
creates a whole new Person struct using all the data from the existing person struct with the new bit of data you want to change, and replace the old person struct in the list with the new one you've made or
gets the person out of the list into a temporary variable, changes the name, puts the temp variable back into the list
As an academic exercise I suppose it's teaching you about value types but it's a bit abstruse; perhaps your teacher is hoping you will pick up on the fact that accessing list[x] creates a copy of what is in the list at x. As there is no point editing a copy (and then throwing the copy away, as a direct edit would do) the compiler warns you that it's not possible.
You are getting the error because structs are value type.
When you do info[i] it returns value of the element at i rather than the reference to it. Modifying this value by calling setter doesn't change anything in the actual struct instance. Hence the error.
A naive workaround would be
info[i]=new person{name= Console.ReadLine()};
If not for an assignment, you should definetely use classes in these cases

C# read value from user console.read [duplicate]

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
You need to typecast the input. try using the following
int input = Convert.ToInt32(Console.ReadLine());
It will throw exception if the value is non-numeric.
Edit
I understand that the above is a quick one. I would like to improve my answer:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Use this simple line:
int x = int.Parse(Console.ReadLine());
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
I used int intTemp = Convert.ToInt32(Console.ReadLine()); and it worked well, here's my example:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}
Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());
I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.

how do i use an array in a switch statement in c#?

So i am new to programming so im pretty confused about this. I created an array and tried to use it inside of a switch statement:
string[] General = new string[5];
{
General[0] = "help";
General[1] = "commands";
General[2] = "hello";
General[3] = "info";
General[4] = "quit";
}
switch(General)
{
case 0:
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("This is a new program. Therefore the amount of commands are limited. \nIt can do simple things. For example, if you say 'tell the time' then it will tell the time\n");
Console.ForegroundColor = oldColor;
continue;
}
}
As far as i am aware there are no problems with this. However, when i run the code i am greeted with this error : "A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type"
I am genuinely stuck with this and i cant find any answers on the internet so any help will be greatly appreciated. Thanks
It sounds like what you are looking for is an enum.
public enum General {
help = 0,
commands = 1,
hello = 2,
info = 3,
quit = 4
}
Then you can use a switch statement just fine :).
// variable to switch
General myGeneral;
// myGeneral is set to something
switch(myGeneral)
{
case General.help:
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("This is a new program. Therefore the amount of commands are limited. \nIt can do simple things. For example, if you say 'tell the time' then it will tell the time\n");
Console.ForegroundColor = oldColor;
break;
}
You are doing the switch statement on the entire array, opposed to a single entry in the array.
Assuming you are trying to write all of the available inputs you could do
string[] General = new string[5];
{
General[0] = "help";
General[1] = "commands";
General[2] = "hello";
General[3] = "info";
General[4] = "quit";
}
foreach(var option in General)
{
switch(option)
{
case "help":
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("This is a new program. Therefore the amount of commands are limited. \nIt can do simple things. For example, if you say 'tell the time' then it will tell the time\n");
Console.ForegroundColor = oldColor;
break;
}
case "commands":
{
//Do some stuff
break;
}
//etc etc
}
}
The parameter in the switch statement should be the user input, not your optional values, for example:
int input = 0; // get the user input somehow
switch (input)
{
case 0:
{
// Do stuff, and remember to return or break
}
// Other cases
}
Also, this is a perfect use case for an Enum. That would look something like this:
public enum General
{
HELP = 0,
COMMANDS = 1,
HELLO = 2,
INFO = 3,
QUIT = 4
}
int input = 0; // get the user input somehow
switch (input)
{
case General.HELP: //Notice the difference?
{
// Do stuff, and remember to return or break
}
// Other cases
}
This makes your intention very clear, and therefore makes your code more readable and more maintainable. You can't do this with your array, because even though you declare your array in your code, it is still variable and therefore its state at the switch statement is not known at compile time. Enums are immutable, and therefore their values are known at compile time and can be used in switch statements.

Reading an integer from user input

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I know that Console.ReadLine(); only takes a char/string. So in short I am looking for the integer version of this.
Just to give you an idea of what I'm doing exactly:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
Console.ReadLine(); // Needs to take in int rather than string or char.
I have been looking for quite a while for this. I have found a lot on C but not C#. I did find however a thread, on another site, that suggested to convert from char to int. I'm sure there has to be a more direct way than converting.
You can convert the string to integer using Convert.ToInt32() function
int intTemp = Convert.ToInt32(Console.ReadLine());
I would suggest you use TryParse:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
string input = Console.ReadLine();
int number;
Int32.TryParse(input, out number);
This way, your application does not throw an exception, if you try to parse something like "1q" or "23e", because somebody made a faulty input.
Int32.TryParse returns a boolean value, so you can use it in an if statement, to see whether or not you need to branch of your code:
int number;
if(!Int32.TryParse(input, out number))
{
//no, not able to parse, repeat, throw exception, use fallback value?
}
To your question: You will not find a solution to read an integer because ReadLine() reads the whole command line, threfor returns a string. What you can do is, try to convert this input into and int16/32/64 variable.
There are several methods for this:
Int.Parse()
Convert.ToInt()
Int.TryParse()
If you are in doubt about the input, which is to be converted, always go for the TryParse methods, no matter if you try to parse strings, int variable or what not.
Update
In C# 7.0 out variables can be declared directly where they are passed in as an argument, so the above code could be condensed into this:
if(Int32.TryParse(input, out int number))
{
/* Yes input could be parsed and we can now use number in this code block
scope */
}
else
{
/* No, input could not be parsed to an integer */
}
A complete example would look like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var foo = Console.ReadLine();
if (int.TryParse(foo, out int number1)) {
Console.WriteLine($"{number1} is a number");
}
else
{
Console.WriteLine($"{foo} is not a number");
}
Console.WriteLine($"The value of the variable {nameof(number1)} is {number1}");
Console.ReadLine();
}
}
Here you can see, that the variable number1 does get initialized even if the input is not a number and has the value 0 regardless, so it is valid even outside the declaring if block
You need to typecast the input. try using the following
int input = Convert.ToInt32(Console.ReadLine());
It will throw exception if the value is non-numeric.
Edit
I understand that the above is a quick one. I would like to improve my answer:
String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
switch(selectedOption)
{
case 1:
//your code here.
break;
case 2:
//another one.
break;
//. and so on, default..
}
}
else
{
//print error indicating non-numeric input is unsupported or something more meaningful.
}
int op = 0;
string in = string.Empty;
do
{
Console.WriteLine("enter choice");
in = Console.ReadLine();
} while (!int.TryParse(in, out op));
Use this simple line:
int x = int.Parse(Console.ReadLine());
I didn't see a good and complete answer to your question, so I will show a more complete example. There are some methods posted showing how to get integer input from the user, but whenever you do this you usually also need to
validate the input
display an error message if invalid input
is given, and
loop through until a valid input is given.
This example shows how to get an integer value from the user that is equal to or greater than 1. If invalid input is given, it will catch the error, display an error message, and request the user to try again for a correct input.
static void Main(string[] args)
{
int intUserInput = 0;
bool validUserInput = false;
while (validUserInput == false)
{
try
{
Console.Write("Please enter an integer value greater than or equal to 1: ");
intUserInput = int.Parse(Console.ReadLine()); //try to parse the user input to an int variable
}
catch (Exception e) //catch exception for invalid input, such as a letter
{
Console.WriteLine(e.Message);
}
if (intUserInput >= 1) { validUserInput = true; }
else { Console.WriteLine(intUserInput + " is not a valid input, please enter an integer greater than 0."); }
} //end while
Console.WriteLine("You entered " + intUserInput);
Console.WriteLine("Press any key to exit ");
Console.ReadKey();
} //end main
In your question it looks like you wanted to use this for menu options. So if you wanted to get int input for choosing a menu option you could change the if statement to
if ( (intUserInput >= 1) && (intUserInput <= 4) )
This would work if you needed the user to pick an option of 1, 2, 3, or 4.
I used int intTemp = Convert.ToInt32(Console.ReadLine()); and it worked well, here's my example:
int balance = 10000;
int retrieve = 0;
Console.Write("Hello, write the amount you want to retrieve: ");
retrieve = Convert.ToInt32(Console.ReadLine());
Better way is to use TryParse:
Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}
Try this it will not throw exception and user can try again:
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice = 0;
while (!Int32.TryParse(Console.ReadLine(), out choice))
{
Console.WriteLine("Wrong input! Enter choice number again:");
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number from 1 to 10");
int counter = Convert.ToInt32(Console.ReadLine());
//Here is your variable
Console.WriteLine("The numbers start from");
do
{
counter++;
Console.Write(counter + ", ");
} while (counter < 100);
Console.ReadKey();
}
You could create your own ReadInt function, that only allows numbers
(this function is probably not the best way to go about this, but does the job)
public static int ReadInt()
{
string allowedChars = "0123456789";
ConsoleKeyInfo read = new ConsoleKeyInfo();
List<char> outInt = new List<char>();
while(!(read.Key == ConsoleKey.Enter && outInt.Count > 0))
{
read = Console.ReadKey(true);
if (allowedChars.Contains(read.KeyChar.ToString()))
{
outInt.Add(read.KeyChar);
Console.Write(read.KeyChar.ToString());
}
if(read.Key == ConsoleKey.Backspace)
{
if(outInt.Count > 0)
{
outInt.RemoveAt(outInt.Count - 1);
Console.CursorLeft--;
Console.Write(" ");
Console.CursorLeft--;
}
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
return int.Parse(new string(outInt.ToArray()));
}
Declare a variable that will contain the value of the user input :
Ex :
int userInput = Convert.ToInt32(Console.ReadLine());
I know this question is old, but with some newer C# features like lambda expressions, here's what I actually implemented for my project today:
private static async Task Main()
{
// -- More of my code here
Console.WriteLine("1. Add account.");
Console.WriteLine("2. View accounts.");
int choice = ReadInt("Please enter your choice: ");
// -- Code that uses the choice variable
}
// I have this as a public function in a utility class,
// but you could use it directly in Program.cs
private static int ReadInt(string prompt)
{
string? text;
do
{
Console.Write(prompt);
text = Console.ReadLine();
} while (text == null || !text.Where(c => char.IsNumber(c)).Any());
return int.Parse(new string(text.Where(c => char.IsNumber(c)).ToArray()));
}
The difference here is that if you accidentally type a number and any other text along with that number, only the number is parsed.
You could just go ahead and try :
Console.WriteLine("1. Add account.");
Console.WriteLine("Enter choice: ");
int choice=int.Parse(Console.ReadLine());
That should work for the case statement.
It works with the switch statement and doesn't throw an exception.

How to use .ToLower() properly in this case?

So what I'm attempting to do is have this program ignore a user's letter case when entered. I see how to use .ToLower(); however I'm not understanding how to do this the right way.
Here's what I have now, am I close? I've read a bunch of tutorials online however they are mostly just standalone programs that convert user input to lower. Is there a way to enable this globally?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Choose_Your_Color
{
class Program
{
enum Color
{
red,
orange,
blue,
black,
white,
green,
purple,
yellow
}
static void Main(string[] args)
{
Color favorite;
while (true)
{
Console.WriteLine("What color do you choose?");
if (Enum.TryParse(Console.ReadLine(), out favorite))
if (string.compare(favorite , Enum , true) == 0){
Continue;
}
{
switch (favorite)
{
case Color.red:
Console.WriteLine("You chose red!");
break;
case Color.orange:
Console.WriteLine("you chose orange!!!!!!");
break;
case Color.blue:
Console.WriteLine("YOU CHOSE BLUEEEE!!");
break;
case Color.black:
Console.WriteLine("you chose black");
break;
case Color.white:
Console.WriteLine(" you chose white!");
break;
case Color.green:
Console.WriteLine("you chose green!!!!!");
break;
case Color.purple:
Console.WriteLine("you chose purple!!");
break;
case Color.yellow:
Console.WriteLine("you chose yellow!!!");
break;
}
}
else
{
Console.WriteLine("That's not a color!");
}
}
}
}
}
You just need to do:
if (Enum.TryParse(Console.ReadLine().ToLower(), out favorite))
You don't need that nested if, you can just remove it.Also you have to add a break to the end of your if block, so it will break your loop after user type a valid value otherwise the loop will never end.
Enum.TryParse accepts a parameter to ignore case:
Enum.TryParse(Console.ReadLine(), true, out favorite);
Just change this;
if (Enum.TryParse(Console.ReadLine(), out favorite))
to
if (Enum.TryParse(Console.ReadLine().ToLower(), out favorite))
Console.ReadLine() returns a string, this will call to lower on that value ensuring that all the input is lower cased.
Why do you have this line?
if (string.compare(favorite , Enum , true) == 0){
Continue;
}
I don't think there is any reason for it. Enum.TryParse should either return false meaning the input wasn't one of the enums and you won't go into the switch statement OR favorite will be one of the enum values and you'll go into one of the cases in your switch statement.
Note that this overload of TryParse allows you to ignore the case of the input string, so you could just write this as:
if (Enum.TryParse(Console.ReadLine(), true, out favorite))
String.ToLower() will return the string value as lowercase.
if (Enum.TryParse(Console.ReadLine().ToLower(), out favorite))

Categories