Anthony
Anthony

Reputation: 923

Getting the integer value from enum

I am working on a basic Battleship game to help my C# skills. Right now I am having a little trouble with enum. I have:

enum game : int
{
    a=1,
    b=2,
    c=3,
}

I would like the player to pass the input "C" and some code return the integer 3. How would I set it up for it to take a string var (string pick;) and convert it to the correct int using this enum? The book I am reading on this is bit confusing

Upvotes: 29

Views: 83025

Answers (5)

mmacneill123
mmacneill123

Reputation: 33

The answer is fine but the syntax is messy.

Much neater is something like this:

    public DataSet GetBasketAudit(enmAuditPeriod auditPeriod)
    {
        int auditParam =Convert.ToInt32(auditPeriod) ;

Upvotes: -1

Jeff
Jeff

Reputation: 1744

If you're not sure that the incoming string would contain a valid enum value, you can use Enum.TryParse() to try to do the parsing. If it's not valid, this will just return false, instead of throwing an exception.

jp

Upvotes: 4

Muad'Dib
Muad'Dib

Reputation: 29256

// convert string to enum, invalid cast will throw an exception
game myenum =(game) Enum.Parse(typeof(game), mystring ); 

// convert an enum to an int
int val = (int) myenum;

// convert an enum to an int
int n = (int) game.a; 

Upvotes: 15

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234644

Just parse the string and cast to int.

var number = (int)((game) Enum.Parse(typeof(game), pick));

Upvotes: 65

knoopx
knoopx

Reputation: 17410

just typecasting?

int a = (int) game.a

Upvotes: 7

Related Questions