Reputation: 156
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;
}
}
}
}
}
Upvotes: 0
Views: 795
Reputation: 112259
An enum value is automatically converted to an enum name when converted to string. Therefore you can write
foreach (Automerkit enumValue in Enum.GetValues(typeof(Automerkit))) {
WriteLine($"{(int)enumValue} = {enumValue}");
}
Note that the foreach statement automatically converts the element type (object
returned by GetValues
here) to the type of the iteration variable (Automerkit
).
For more information, see The foreach statement section of the C# language specification. The parameter of the WriteLine
uses String interpolation in C# (Microsoft Docs).
Upvotes: 3
Reputation: 270790
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)}");
}
Upvotes: 1
Reputation: 6103
You can use the Enum.GetNames
function and then parse the name to get the int
value.
foreach (var merkkiluettelo in Enum.GetNames(typeof(Automerkit)))
{
Enum.TryParse(merkkiluettelo, out Automerkit a);
Console.WriteLine($"{(int)a} = {merkkiluettelo}");
}
Upvotes: 2