Leo
Leo

Reputation: 267

Difficulties with dynamically identifying enum member

    public enum Levels
    {
        LevelState1 = 0,
        LevelState2 = 1,
        LevelState3 = 2
    }
    private Levels currentLevel;
    public void ChooseLevel(Levels levelstate)
    {
        switch (levelstate)
        {
            case Levels.LevelState1:
                currentLevel = Levels.LevelState1;
        ...
                break;
            case Levels.LevelState2:
                currentLevel = Levels.LevelState2;
        ...     
                break;
            case Levels.LevelState3:
                currentLevel = Levels.LevelState3;
        ...
                break;
        }
    }

//The variable CurrentLevel is an integer
ChooseLevel(Levels."LevelState"+game1.CurrentLevel.ToString());

I always get this error message in the last line: Identifier expected What should I change? I don't know how to fix this problem.

Upvotes: 0

Views: 93

Answers (3)

Sarkilas
Sarkilas

Reputation: 86

I feel that you are overcomplicating things. You can do this much simpler in a way similar to this:

    public enum Levels
{
    LevelState1 = 1,
    LevelState2 = 2,
    LevelState3 = 3
}
private Levels currentLevel;
public void ChooseLevel(int state)
{
    currentLevel = (Levels)state; // casting to enum from int
    // process level or whatever here
}

//The variable CurrentLevel is an integer
ChooseLevel(game1.CurrentLevel);

Since your CurrentLevel variable is an integer, you can easily cast it to your enum by binding level states to actual integer values within the level range. So instead of starting at 0 in your enum, you start at the first level value (which in your case is 1, no?).

Hope this helps.

Upvotes: 0

Zbigniew
Zbigniew

Reputation: 27594

ChooseLevel expectes enum argument, whereas you're using a mixture of enum and string, you'll have to parse it:

Levels game1Level = (Levels)Enum.Parse(typeof(Levels), "LevelState" + game1.CurrentLevel);
ChooseLevel(game1Level);

You can also use Enum.TryParse

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300549

Either wrap this in a try/catch:

Levels level = (Levels)Enum.Parse(typeof(Levels), 
                                       "LevelState" + game1.CurrentLevel.ToString());
ChooseLevel(level);

Or use Enum.TryParse()

Upvotes: 2

Related Questions