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
ENUM values are represented internally as integers. Trailing spaces are automatically stripped from ENUM values on table creation.
In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays.
Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.
Enums cannot inherit from other enums. In fact all enums must actually inherit from System. Enum . C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.
Getting Integer from Enum. On the other hand, to get the integer value from an enum, one can do as follows, by using the getValue method. The getValue method simply returns the internal value of the enum that we store within the value variable.
Get integer value from enum member name in C# 1 Using Casting#N#We can get the constant integer value simply by casting the enum member name. This is demonstrated... 2 Using Convert.ChangeType () method#N#To get the enum’s underlying value, we can use the Convert.GetTypeCode () method. 3 Using Object.GetHashCode () method More ...
On the other hand, to get the integer value from an enum, one can do as follows, by using the getValue method. ProductType productType = ProductType.DATABASES; int productTypeId = productType.getValue (); // productTypeId = 3 The getValue method simply returns the internal value of the enum that we store within the value variable.
Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:
Just parse the string and cast to int.
var number = (int)((game) Enum.Parse(typeof(game), pick));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With