M.Kesküll M.Kesküll - 2 months ago 8
C# Question

Cannot convert from int to enum

using Logic;
using System;

namespace Software
{
class Program
{
static void Main(string[] args)
{
int selected;
do
{
selected = MainMenu.Display();
if (IsPrint(selected)) PrintNumbers.Start();
if (IsGuess(selected)) GuessingGame.Start();
} while (selected !=(int) MenuItem.Wrong);
}
static bool IsGuess(MenuItem i)
{
return i == MenuItem.Game;
}

static bool IsPrint(MenuItem i)
{
return i == MenuItem.Print;
}
}
}





namespace Logic
{
public enum MenuItem
{
Print,
Game,
Exit,
Wrong
}
}

Answer

You have two ways to solve this:

First Approach:

Cast the integer local variable to the required MenuItem type:

IsPrint((MenuItem)selected)

and

IsPrint((MenuItem)selected)

Second Approach:

Change selected to be of type MenuItem:

static void Main(string[] args)
{
    MenuItem selected;
    do
    {
        selected = (MenuItem)MainMenu.Display();
        if (IsPrint(selected)) 
           PrintNumbers.Start();

        if (IsGuess(selected)) 
           GuessingGame.Start();

    } while (selected != MenuItem.Wrong);
}
Comments