DEV Community

Discussion on: Is there a way to make a new enum from an array of `String`s?

 
baenencalin profile image
Calin Baenen

I'm making a command-line interface, and I have a list of commands.

I want to use a list of command strings to generate an enum.
Why do this when you have the list?
Because this:

switch(cmd) {
    case COMMANDS[0]: /* ... */
}
Enter fullscreen mode Exit fullscreen mode

It throws an error that the case isn't constant (as I GUESS it should rightfully do so), therefore, I need to manually right all of the commands down again.

Thread Thread
 
redcreator37 profile image
RedCreator37

Ah, this makes sense. Since it won't let you use plain string arrays, you could try a more OOP approach using Dictionaries and custom command classes.

In the example, there's a dictionary containing all available commands. Each command implements the ICommand interface (and the Execute() method, which gets executed by the while loop in Main). You can add fields to the ICommand interface to store the command's name or usage description if you want.

This doesn't directly answer your question but hopefully helps in some way.

Thread Thread
 
baenencalin profile image
Calin Baenen

Doesn't making a new class for every command seem bloated?
Otherwise, this does help.

Thread Thread
 
baenencalin profile image
Calin Baenen

Thanks for the help.

Thread Thread
 
baenencalin profile image
Calin Baenen

Is there a way I can convert all the String constants of a class to a String[]?

 
redcreator37 profile image
RedCreator37

Doesn't making a new class for every command seem bloated?
Otherwise, this does help.

It's actually advisable because it makes adding new functionality / commands easier and the code is more readable/easier to maintain. The performance impact is minimal (C# is really good at optimizations).