Get int value from enum in C#
Just cast the enum, e.g.
int something = (int) Question.Role;
The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int
.
However, as cecilphillip points out, enums can have different underlying types.
If an enum is declared as a uint
, long
, or ulong
, it should be cast to the type of the enum; e.g. for
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
you should use
long something = (long)StarsInMilkyWay.Wolf424B;
Getting enum associated with int value
EDIT August 2018
Today I would implement this as follows
public enum LegNo {
NO_LEG(-1), LEG_ONE(1), LEG_TWO(2);
private final int value;
LegNo(int value) {
this.value = value;
}
public static Optional<LegNo> valueOf(int value) {
return Arrays.stream(values())
.filter(legNo -> legNo.value == value)
.findFirst();
}
}
You'll have to maintain a mapping inside the enum.
public enum LegNo {
NO_LEG(-1), LEG_ONE(1), LEG_TWO(2);
private int legNo;
private static Map<Integer, LegNo> map = new HashMap<Integer, LegNo>();
static {
for (LegNo legEnum : LegNo.values()) {
map.put(legEnum.legNo, legEnum);
}
}
private LegNo(final int leg) { legNo = leg; }
public static LegNo valueOf(int legNo) {
return map.get(legNo);
}
}
The static block will be invoked only once, so there is practically no performance issue here.
EDIT: Renamed the method to valueOf
as it is more inline with other Java classes.
Associate enum value to integer
It is possible, but not by invoking the enum
's constructor, as it's available only within the enum itself.
What you can do is add a static
method in your enum
that retrieves the correct instance based on a given value, e.g. ZERO
if the given value is 0
.
Then you'd invoke that method in your other class when given the int
argument.
Self contained example
public class Main {
static enum Numbers {
// various instances associated with integers or not
ZERO(0),ONE(1),FORTY_TWO(42), DEFAULT;
// int value
private int value;
// empty constructor for default value
Numbers() {}
// constructor with value
Numbers(int value) {
this.value = value;
}
// getter for value
public int getValue() {
return value;
}
// utility method to retrieve instance by int value
public static Numbers forValue(int value) {
// iterating values
for (Numbers n: values()) {
// matches argument
if (n.getValue() == value) return n;
}
// no match, returning DEFAULT
return DEFAULT;
}
}
public static void main(String[] args) throws Exception {
System.out.println(Numbers.forValue(42));
System.out.println(Numbers.forValue(10));
}
}
Output
FORTY_TWO
DEFAULT
How to get the int for enum value in Enumeration
To answer your question "how can I get the integer for string value":
To convert from a string into an enum, and then convert the resulting enum to an int, you can do this:
public enum Animals
{
dog = 0,
cat = 1,
rat = 2
}
...
Animals answer;
if (Enum.TryParse("CAT", true, out answer))
{
int value = (int) answer;
Console.WriteLine(value);
}
By the way, normal enum naming convention dictates that you should not pluralize your enum name unless it represents flag values (powers of two) where multiple bits can be set - so you should call it Animal
, not Animals
.
give an int number to enum and get its related value as string in c++
If you really can't use an array (which would be by far the easiest way), you could build a function with a switch case:
enum difficulty
{
Easy = 1,
Normal,
Hard
};
std::string diff_name(difficulty d) {
switch(d) {
case Easy: return "Easy";
case Normal: return "Normal";
case Hard: return "Hard";
default: return std::string();
}
}
And then in main
you could do
cout << "choice: ";
cin >> choice;
std::cout << "You chose: "
<< diff_name(static_cast<difficulty>(choice)) << std::endl;
associating int value to enum and getting corresponding int value
You do not need the map to retrieve code
from an enum
object, because the call of TAXSLAB.getCode(s)
produces the same value as s.getCode()
:
TAXSLAB s = ...
int c1 = TAXSLAB.getCode(s);
int c2 = s.getCode();
// c1 == c2 here
int code
is a field of enum TAXSLAB
object, so you can get it directly.
This works for values associated with an enum
from within the enum
. If you need to associate a value with an enum
outside the enum
, the most performant way of doing it is by using EnumMap
class designed specifically for this purpose.
How to get integer values from Enum in c#
Basically you cam use Enum.Parse
to parse the string and then cast to int like below :
var str = "value1";
var value = (int)Enum.Parse<MyEnum>(str);
Fiddle
Related Topics
Location of Hibernate.Cfg.Xml in Project
Why Are New Java.Util.Arrays Methods in Java 8 Not Overloaded for All the Primitive Types
Iteratively Compute the Cartesian Product of an Arbitrary Number of Sets
Minimum Spring Version Compatible with Java 11
How to Change the Highlight Color of a Focused Jcombobox
Junit - Run Set Up Method Once
How to Call Methods in Constructor in Java
Initializing an Array in Java Using the 'Advanced' for Each Loop
How to Make a List with Checkboxes in Java Swing
Allowing the "Enter" Key to Press the Submit Button, as Opposed to Only Using Mouseclick
@Preupdate and @Prepersist in Hibernate/JPA (Using Session)
Java User.Home Is Being Set to %Userprofile% and Not Being Resolved
Java 9, Compatability Issue with Classloader.Getsystemclassloader