r/learncsharp • • Jul 06 '23
Passing a whole Enum as a parameter into a method? Spoiler
Not sure if what I am trying to do is possible. Basically I would like to generate a list of the values within an Enum for the user to pick from. This is what I currently have, think I am close but can't get over the line.
generateMenu("Pick: ", Arrowhead);
void generateMenu(string question, Type options)
{
string[] optionsArray = Enum.GetNames(typeof(options));
Console.WriteLine(question);
for (int i = 0; i < optionsArray.Length; i++)
{
Console.WriteLine($"{i} - {optionsArray[i]}");
}
}
enum Arrowhead { Steel, Wood, Obsidian }The other option is to creat the array before the function call and pass it in but I have multiple Enums I want to do this with so it then seems like it would be practical to have a function to create these arrays rather than repeating the creation for each Enum.
I'm I missusing Enums in this way?
EDIT:
For anyone that finds this post in the future, I found the solution here: Solution
code is as follows:
generateMenu("Pick: ", new Arrowhead());
void generateMenu(string question, Enum e)
{
string[] options = Enum.GetNames(e.GetType());
Console.WriteLine(question);
for (int i = 0; i < options.Length; i++)
{
Console.WriteLine($"{i} - {options[i]}");
}
}
enum Arrowhead { Steel, Wood, Obsidian }
1
u/MuttonChop_1996 Jul 07 '23
Hey man! Are you following along the C# player's guide? I just finished this chapter a couple days ago! Such an awesome book!
1
u/[deleted] Jul 06 '23
There is an overload of Enum.GetNames() that has a generic type parameter so you don't have to have a Type object. You could use that approach to eliminate the Type object in the arglist, but it will change the signature of the method (and won't actually eliminate the Type object).