Since my game has some modes (which should be provided at initialization), so I thought of creating an enum for it. Later on I wanted to get the value of this enum. Below is my code-
enum GameMode : short
{
Stop = 0,
StartSinglePlayer = 4,
StartMultiPlayer = 10,
Debug = 12
}
class Game
{
static short GetValue(GameMode mode)
{
short index = -1;
if (mode == GameMode.Stop)
index = 0;
else if (mode == GameMode.StartSinglePlayer)
index = 4;
else if (mode == GameMode.StartMultiPlayer)
index = 10;
else if (mode == GameMode.Debug)
index = 12;
return index;
}
static void Main(string[] args)
{
var value = GetValue(GameMode.StartMultiPlayer);
}
}
I am curious to know about a better way to do the same, if exist.
Sure, there is a much easier way. Just cast your enum to its underlying numeric data type:
value = (short)mode;
If there are multiple switches like that or if there is different behavior for each mode, then I would recommend using polymorphism instead of enum with switch. If the switch in your example is only place where GameMode
is used, Heinzi's solution is simpler. But I would at least keep this in mind for the future if you encounter situation where you want to do different stuff with GameMode
than what you are showing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With