Reputation: 923
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
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
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
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
Reputation: 234644
Just parse the string and cast to int.
var number = (int)((game) Enum.Parse(typeof(game), pick));
Upvotes: 65