tags:

views:

149

answers:

4

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

+1  A: 

just typecasting?

int a = (int) game.a
knoopx
+6  A: 

Just parse the string and cast to int.

var number = (int)((game) Enum.Parse(typeof(game), pick));
Martinho Fernandes
works great thanks
Anthony
+4  A: 
// 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;
Muad'Dib
+2  A: 

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

Jeff