To get an enum value, select a member and access the value representation your language defines: in C#, cast the member to its underlying numeric type; in Python, use .value; and in Java, read a field you define for that purpose. The exact step depends on the language and on whether you need the member’s number, its name, or a separate display value.
What You’ll Need
- The enum declaration and the programming language it uses. A member’s underlying value may be assigned automatically or explicitly, depending on the language.
- A clear idea of the result you need: a numeric code, the member name, or a user-facing label. These are not necessarily the same thing.
- A compiler or runtime for your language if you want to run the examples. The examples below use C#, Java, Python, and TypeScript; they do not require a particular editor.
Step-by-Step
- Find the enum declaration and identify the member. An enum defines a fixed set of named choices. For example, a status enum might contain
Pending,Paid, andShipped. Read the declaration before retrieving a value: it tells you whether each member has an explicit number or string, whether values are assigned automatically, and whether there is a separate label or field. Do not assume a member’s position in the declaration is its intended application value. - Decide which kind of value you want. If you are saving a status to a database or sending it through an API, you may need a stable numeric or string code. If you are showing a choice in a log, you may need its name. If you are displaying it to a person, the best result may be a label such as “Payment received,” rather than either the enum’s name or its underlying code. A reliable implementation keeps these purposes distinct instead of treating every representation as interchangeable.
- In C#, cast a numeric enum member to its underlying type. C# enums have an integral underlying type, which is
intunless the declaration specifies another integral type. This example assigns explicit numbers so the intended values are clear:
enum OrderStatus
{
Pending = 1,
Paid = 2,
Shipped = 4
}
OrderStatus status = OrderStatus.Paid;
int value = (int)status;
Here, value is 2. The cast retrieves the underlying number; it does not return the text Paid. If the enum declares a different underlying type, such as byte, use a compatible variable type or an appropriate conversion. For example, casting a byte-based enum to int is allowed, but converting an arbitrary number into an enum does not prove that the number represents a declared member.
- In C#, get a member name from a value only after checking it. If you have a numeric value and want the corresponding declared name, you can use
Enum.GetName. Check whether the value is defined first when you expect only ordinary enum members:
int value = 2;
if (Enum.IsDefined(typeof(OrderStatus), value))
{
string name = Enum.GetName(typeof(OrderStatus), value);
}
For this declaration, the name is Paid. An integer can still be cast to an enum even when no member has that number, so validation matters when input comes from a file, a form, or a network request. This check has an important limitation for flags enums: a valid combination of flags may not equal any single named member, so Enum.IsDefined can reject a combination that your application considers valid.
- In Python, read the member’s
.valueattribute. Python’sEnumkeeps the member name and its associated value separately:
from enum import Enum
class OrderStatus(Enum):
PENDING = 1
PAID = 2
SHIPPED = 4
status = OrderStatus.PAID
value = status.value
name = status.name
Here, value is 2 and name is PAID. Use .value for the associated value and .name for the declared member name. If you need the member for a value you already have, you can look it up with OrderStatus(2); that returns OrderStatus.PAID, while a value not defined by the enum raises ValueError. Handle that exception if the input may be invalid.
- In Java, do not mistake
ordinal()for an assigned business value. Every Java enum member has an ordinal representing its zero-based position in the declaration. For example,PAID.ordinal()is1ifPAIDis the second member. That position can change if someone reorders the declaration, so it is usually unsuitable as a stored code or an API value. When you need a stable code, declare a field and provide an accessor:
enum OrderStatus {
PENDING(1), PAID(2), SHIPPED(4);
private final int code;
OrderStatus(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
int value = OrderStatus.PAID.getCode();
In this example, the returned value is 2. Use OrderStatus.PAID.name() if you need the declared name. If you receive a code and need the enum member, search for a matching getCode() value or write a dedicated lookup method; Java does not automatically map an arbitrary custom field back to a member.
- In TypeScript, read a member directly, and account for the enum kind. A numeric enum can have assigned numeric values:
enum OrderStatus {
Pending = 1,
Paid = 2,
Shipped = 4
}
const value = OrderStatus.Paid;
const name = OrderStatus[2];
Here, value is 2, and numeric enum reverse mapping makes name equal to Paid. A string enum behaves differently:
enum TextStatus {
Pending = 'pending',
Paid = 'paid'
}
const value = TextStatus.Paid;
That value is the string paid; string enums do not provide the same number-to-name reverse mapping. JavaScript itself has no built-in enum syntax, so JavaScript projects often use objects or constants instead. Check the actual object shape rather than expecting TypeScript enum behavior in plain JavaScript.
- Convert carefully when a value comes from outside your code. A form field, JSON payload, or database column may provide a string even when your enum uses numbers, or may contain a code that is no longer supported. Parse or look up the input, verify that it maps to a valid member, and decide what your application should do if it does not. Avoid silently converting unknown input to the first enum member: that can turn bad data into a plausible but incorrect status.
- Keep persisted values stable. If a code is saved and read later, assign explicit values or use explicit string codes instead of depending on declaration order. Once a value is used in saved records or shared with another system, changing it can make old data mean something different. Treat changes to those codes as compatibility changes and update readers and writers together.
Common Mistakes
Confusing a name with a value. Paid, 2, and paid might all refer to one status, but they are different representations. Make sure the receiving method or system expects the representation you are passing. A database column designed for a number will not necessarily accept a member name.
Assuming every enum starts at zero or one. Some languages or declarations assign values automatically; others let you choose. In C#, implicit numeric values typically begin at zero and increase, while an explicit assignment affects subsequent implicit members. In Java, ordinal() starts at zero and follows declaration order, regardless of a custom field. Inspect the declaration instead of guessing.
Using a declaration position as a permanent identifier. Inserting a member before another one can change its ordinal or automatically assigned number. That can break stored records, messages, or integrations. Use deliberately assigned codes for data that must remain stable.
Trusting a cast or conversion to validate input. A numeric value can fit the enum’s underlying type without matching any declared member. Validate external values and decide how unknown values should be handled. Also remember that bit flags can represent valid combinations that do not appear as individual named members.
Expecting every language to support reverse lookup. TypeScript numeric enums provide reverse mapping, while string enums do not. Python constructs a member from its value but raises an error when there is no match. Java custom fields need an explicit lookup. Use the language’s actual behavior rather than copying a lookup pattern from another language.
Tips
Give enum members explicit values when those values cross a long-term boundary, such as a database, exported file, or external API. Choose the type that matches the contract, document the mapping, and avoid reusing a code that may already exist in old data. If a system expects strings, stable strings can be easier to inspect in logs, but they still need a documented mapping and consistent spelling.
Keep display text separate from identifiers. Enum names are often written for developers and may use uppercase letters, underscores, or abbreviations. A label shown in an interface can be changed for clarity or translation without changing the stored code. Put that mapping in a deliberate location, such as a formatter, resource file, or property, rather than making other parts of the program depend on presentation text.
Use the enum type when the value is in your program, and convert at boundaries. For example, parse incoming data into a known member, validate it, and then pass the typed member through your application. Convert it to the required number or string only when saving or communicating. This reduces accidental comparisons between a raw number and a member name.
When debugging, inspect both the member and its representation. In a log, record the enum name and the code if both help explain the issue. If a number appears unexpectedly, compare it with the declaration and check whether a conversion, default value, or stale database record supplied it.
Troubleshooting
The compiler says the conversion is invalid. Check the enum’s language and declared underlying type. In C#, use a cast for a numeric enum and ensure the destination type is compatible. In Python, use the member’s .value attribute rather than treating the enum member itself as a number; use IntEnum only when integer behavior is deliberately appropriate.
You get a number but expected text. You have retrieved the underlying value. Use the member name or a separate label instead. In C#, call ToString() on a valid enum member; in Python, use .name; in Java, use name(); and in TypeScript, use the numeric reverse mapping only for a numeric enum. These names are identifiers, not automatically polished user-facing text.
A lookup returns no member or throws an error. Verify the input’s type and exact value. A string such as 2 is not always the same as the number 2, and a label may not match the declared member name. Check for whitespace, capitalization, outdated codes, and values that are absent from the current declaration. Return a clear validation error or use an intentional fallback rather than guessing.
Saved data changes meaning after an update. Look for code that relies on implicit values or declaration positions, especially Java ordinal(). Compare the current enum with the version that wrote the data. Restore a stable mapping, migrate affected records if needed, and preserve old codes when compatibility requires it.
A flags combination fails a validity check. In C#, a combined flags value may be made from valid individual bits without being a separately declared member. Check whether the bits are allowed according to the enum’s design rather than requiring every combination to be listed as a named value. Keep this rule separate from validation for an ordinary, single-choice enum.
Frequently Asked Questions
Is an enum’s value the same as its name?
No. The name is the identifier written in the declaration, while the value may be a number, string, or associated field. Some languages also calculate a position, such as Java’s ordinal, which is another distinct thing.
How do I get the value of an enum in C#?
Cast the member to its underlying integral type, commonly int. If you need its text name, use ToString() on the member. Validate numbers received from outside the program before relying on them as declared members.
How do I get an enum value in Python?
Access the selected member’s .value attribute. Use .name when you need its declared identifier. To look up a member from a value, call the enum class with that value and handle ValueError if it is unknown.
Should I use Java ordinal() as an ID?
Usually not. It represents declaration order, so rearranging enum members can change the result. Give each member a stable field, such as a numeric code, and expose that field through a method when the value is used for storage or communication.
Can I get the name from a TypeScript enum value?
For a numeric enum, indexing the enum object with the number can return the member name. String enums do not have the same reverse mapping, so keep an explicit lookup if you need to map a string value back to a name.
What should I return for an unknown enum value?
Choose behavior that fits the application: reject the input with a clear error, report an unsupported value, or use a documented fallback when it is safe. Do not silently substitute a different valid member, because that can hide corrupt or incompatible data.
Related
- Default Borders in Excel: What They Are and How to Set Them
- Degree Audit Excel Template: Build a Clear Credit Tracker
- Debt Payoff Tracker Excel Template: How to Build One
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Can You Do Text to Columns Vertically in Excel?Not directly: Excel’s Text to Columns command splits text across separate columns, not down separate rows. To split…
- How to Select a Sheet in Excel With Keyboard ShortcutsTo select the next worksheet in Excel for Microsoft 365 on Windows, press Ctrl+Page Down; to select the…
- Power Query Circular Reference: Causes and FixesA Power Query circular reference happens when a query depends on itself, either directly or through other queries,…
- How to Insert a Long Line in Word: 3 Simple MethodsTo insert a long horizontal line in Word, type three hyphens on an otherwise empty line and press…
- COUNTIF for Nonblank Cells in Google Sheets: TipsTo count cells that are not blank in Google Sheets, use =COUNTIF(A2:A100,"<>"). Replace A2:A100 with your range; the…
- Google Sheets in Microsoft Edge: Setup, Features and FixesYes. Google Sheets works in Microsoft Edge: open sheets.google.com, sign in to a Google Account, and create or…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.