Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with enum in C#

Tags:

c#

enums

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.

like image 810
Ravi Joshi Avatar asked Dec 16 '22 00:12

Ravi Joshi


2 Answers

Sure, there is a much easier way. Just cast your enum to its underlying numeric data type:

value = (short)mode;
like image 195
Heinzi Avatar answered Jan 06 '23 12:01

Heinzi


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.

like image 39
Euphoric Avatar answered Jan 06 '23 14:01

Euphoric