I dont know why this so hard no..
I have to check is the user input in Enum.
Now i have two different methods, which tell (False or True) is input in the Enum. I do not want show those things to user, i just want program to print like:
"Your input "user input here" found in Car makers list with name "Audi"
using static System.Console;
namespace EnumAutomerkit
{
enum Automerkit
{
Audi = 100,
BMW = 101,
Citroen = 102,
Mercedes_Benz = 103,
Skoda = 104,
Toyota = 105,
Volkswagen = 106,
Volvo = 107
}
class Program
{
static void Main(string[] args)
{
WriteLine("AUTOMERKIT");
foreach (int luku in Enum.GetValues(typeof(Automerkit)))
WriteLine($"{luku} = {Enum.GetName(typeof(Automerkit), luku)}");
while (true)
{
Console.Write("Valitse automerkki joko numerolla tai nimellä (tyhjä lopettaa): "); //"Choose car maker with number or name (empty breaks): "
string userinput = Console.ReadLine();
int.TryParse(userinput, out int userinput2);//muuttaa annetun stringin int olioksi
Console.WriteLine("{0}: {1}", userinput2, Enum.IsDefined(typeof(Automerkit), userinput2)); //this can check is the number user gave in enum
Console.WriteLine("{0}: {1}", userinput, Enum.IsDefined(typeof(Automerkit), userinput)); //this can check is the text or chars user gave in enum
if (userinput == "")
{
break;
}
}
}
}
}
Answer
You can use the GetName
method to get the name of the enum value associated with its underlying value (there are other methods too, see this post). You only need one foreach
loop, and you can use string interpolation to print in the format value = name
:
foreach (int rawValue in Enum.GetValues(typeof(Automerkit))) {
WriteLine($"{rawValue} = {Enum.GetName(typeof(Automerkit), rawValue)}");
}
No comments:
Post a Comment