30

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

2
  • 2
    It is bad practice to use enums with underlying types other than int and int is the default, so you don't need to make it explicit. Just saying. Commented Dec 26, 2009 at 18:38
  • 3
    isn't your question "get the enum value from an string"? Commented Dec 26, 2009 at 18:40

5 Answers 5

66

Just parse the string and cast to int.

var number = (int)((game) Enum.Parse(typeof(game), pick));
Sign up to request clarification or add additional context in comments.

2 Comments

I see a similar effect with the (int)(game)pick expression
What is pick here?
15
// 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; 

Comments

7

just typecasting?

int a = (int) game.a

1 Comment

No - this isn't what the OP is looking for.
4

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

Comments

-1

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) ;

1 Comment

Not what the OP is trying to solve. Here you are passing in an Enum and converting it. The syntax has to be 'messier' as the OP is converting from a string to the Enums integer counterpart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.