For example, let be enum and let us loop over it
enum Main_menu { NewGame, Options, AboutAuthor, Exit }
static void Main(string[] args)
{
int k = 0;
foreach (Main_menu item in Enum.GetValues(typeof(Main_menu)))
{
Console.Write($"{k} ");
Console.Write(item);
Console.WriteLine();
k++;
}
Console.ReadLine();
}
This enum represents very simple type menu, in the program i work on, i have to use this kind of menus a several times, so i prefer to add it in a separate function, by targeting the part of code with loop and using hotkeys Ctrl+Dot i received following:
enum Main_menu { NewGame, Options, AboutAuthor, Exit }
static void Main(string[] args)
{
int k = 0;
k = LoopOverEnum(k);
Console.ReadLine();
}
private static int LoopOverEnum(int k)
{
foreach (Main_menu item in Enum.GetValues(typeof(Main_menu)))
{
Console.Write($"{k} ");
Console.Write(item);
Console.WriteLine();
k++;
}
return k;
}
}
Now, I want to add enum Main_menu as variable, so, i will be able to apply this loop over every defined enums, I try to do it as follows:
namespace ConsoleApp11
{
class Program
{
enum Main_menu { NewGame, Options, AboutAuthor, Exit }
static void Main(string[] args)
{
int k = 0;
k = LoopOverEnum(k, Main_menu);
Console.ReadLine();
}
private static int LoopOverEnum(int k, enum Main_menu)
{
foreach (Main_menu item in Enum.GetValues(typeof(Main_menu)))
{
Console.Write($"{k} ");
Console.Write(item);
Console.WriteLine();
k++;
}
return k;
}
}
}
But the function's code becomes fully red with different errors. The questions are:
1) How to write the function that loops over enum, in sence that enum is variable ?
2) How to use space in definition of the enum terms ?
How to use space in definition of the enum termsplease clarify this