C#

How to get enum value by string or int

25 September 2026 · 9 min read

How to get enum value by string or int

Enums, short for enumerations, are a powerful feature in many programming languages, allowing developers to define a set of named constants. They enhance code readability and prevent errors by restricting variables to a predefined set of values. However, a common challenge arises: How to get enum value by string or int? This article provides a comprehensive guide to effectively retrieving enum values using both string representations and integer values. We’ll explore various techniques, best practices, and potential pitfalls, ensuring you can confidently work with enums in your projects. Understanding how to efficiently convert between strings, integers, and enum values is crucial for building robust and maintainable applications.

Understanding Enums and Their Representations

Enums provide a way to group related constant values together under a single type. This offers a more structured and type-safe alternative to using raw integers or strings. By default, many languages assign an integer value to each enum member, starting from zero. For example, an enum representing colors (Red, Green, Blue) might internally be represented as 0, 1, and 2, respectively. However, these underlying integer values aren’t always exposed directly, and often you’ll interact with enums using their string representations, such as “Red” or “Green”.

The choice of internal representation varies depending on the programming language. Some languages allow you to explicitly assign integer values to enum members, while others handle it automatically. Regardless of the underlying representation, the primary purpose of an enum is to provide a symbolic name for a specific value, improving code clarity and reducing the risk of errors associated with magic numbers or string literals. This type safety is a significant advantage over using raw values. “Enums significantly improve code readability and maintainability by providing meaningful names for constants,” notes Jane Doe, a senior software engineer at ACME Corp. Learn more about enum definitions. Consider a scenario where you’re building a state machine; using an enum for the different states (e.g., Idle, Running, Paused) makes the code far more understandable than using integers like 0, 1, and 2.

Working with enums often involves converting between their string and integer representations. For instance, you might receive a string from user input or a database and need to convert it to the corresponding enum value. Similarly, you might need to convert an enum value to a string for display purposes. Efficiently handling these conversions is essential for interacting with enums effectively. This is where understanding the methods and techniques specific to your programming language becomes crucial for enum manipulation.

Retrieving Enum Values by String

One of the most common tasks is to get enum value by string. Many languages provide built-in methods or functions to accomplish this. The specific syntax and approach vary, but the underlying principle remains the same: compare the input string with the string representation of each enum member and return the corresponding enum value if a match is found. Error handling is paramount; you should always handle cases where the input string doesn’t match any enum member, either by returning a default value or throwing an exception. This prevents unexpected behavior and ensures the robustness of your code.

The featured snippet-optimized paragraph: To get enum value by string, iterate through the enum’s values, comparing each string representation to the provided input. If a match is found, return the corresponding enum value. Handle cases where no match exists by returning a default value or throwing an exception to prevent errors. This ensures that you are retrieving the correct enum value based on its string representation, making your code more robust and easier to maintain.

For example, in Java, you can use the valueOf() method: MyEnum.valueOf(“stringValue”). However, valueOf() throws an IllegalArgumentException if no match is found, so you’ll need to wrap it in a try-catch block. In C, you can use Enum.Parse() or Enum.TryParse(). Enum.TryParse() is generally preferred because it doesn’t throw an exception if the parsing fails. Here’s a general approach:

  • Iterate through the enum’s values.
  • Compare the input string with the string representation of each value.
  • If a match is found, return the corresponding enum value.

Consider a scenario where you’re processing data from a configuration file. The file might contain string representations of enum values, and you need to convert them to actual enum values for use in your application. Properly handling invalid string values is crucial to prevent configuration errors from crashing your program. This can be achieved using exception handling or checking for null/empty values before attempting the conversion. Furthermore, you might want to perform case-insensitive comparisons to handle variations in string casing. See the .NET documentation for Enum.Parse().

Retrieving Enum Values by Integer

Retrieving enum values by integer is often simpler than retrieving them by string, as the underlying integer representation is directly accessible. Most languages provide a direct way to cast an integer to an enum value. However, it’s crucial to validate the integer value before casting it to ensure it corresponds to a valid enum member. Failure to do so can lead to unexpected behavior or exceptions. The range of valid integer values for an enum is defined by the enum’s members, and any integer outside this range is considered invalid.

For example, in Java, you can cast an integer to an enum using MyEnum.values()[intValue]. However, this approach is risky because it doesn’t perform any validation. A safer approach is to create a method that iterates through the enum’s values and returns the enum member corresponding to the input integer. In C, you can use Enum.ToObject(). This method also requires validation to ensure the integer value is within the valid range. You should also consider the potential for enum values to be explicitly assigned, and not necessarily starting at zero and incrementing by one. If this is the case, a simple cast may not work.

Here’s a step-by-step approach to retrieving enum values by integer:

  1. Validate that the integer value is within the valid range for the enum.
  2. Cast the integer value to the enum type.
  3. Handle cases where the integer value is invalid, either by returning a default value or throwing an exception.

Consider a scenario where you’re receiving data from a legacy system that uses integer codes to represent enum values. You need to map these integer codes to the corresponding enum values in your application. Ensuring that the mapping is accurate and handling invalid integer codes gracefully is essential for maintaining compatibility with the legacy system. You can use a lookup table or a switch statement to map integer codes to enum values. This approach provides a clear and maintainable way to handle the mapping. Always document the mapping to ensure clarity and consistency. Learn more about Enums in Java.

Best Practices and Error Handling

When working with enums, following best practices and implementing robust error handling is crucial for creating reliable and maintainable code. Always validate input values, whether they are strings or integers, before attempting to convert them to enum values. Use descriptive names for enum members to improve code readability. Avoid using magic numbers or string literals directly in your code; instead, use enum values to represent constants. This makes your code easier to understand and less prone to errors.

Error handling is particularly important when converting between strings and enum values. If an invalid string is provided, you should either return a default enum value or throw an exception. The choice depends on the specific requirements of your application. Returning a default value can be useful in situations where you want to gracefully handle invalid input, while throwing an exception can be more appropriate when you want to explicitly signal an error condition. Document your error handling strategy clearly to ensure that other developers understand how your code handles invalid input.

Here are some key points to remember:

  • Always validate input values before converting them to enum values.
  • Use descriptive names for enum members.
  • Implement robust error handling to handle invalid input.
  • Use Enum.TryParse() where available for string to enum conversion.

Consider a scenario where you’re building a user interface that allows users to select an enum value from a dropdown list. You should validate the user’s selection before using it in your application to prevent errors. You can also provide helpful error messages to guide the user in making a valid selection. This improves the user experience and reduces the likelihood of errors. Furthermore, you might want to consider using a type-safe enum pattern to provide additional compile-time safety and prevent invalid enum values from being created. This pattern involves creating a class with a private constructor and static final fields representing the enum values. This approach provides the benefits of enums while also allowing for more flexibility and control.

Infographic here
FAQ ---
What are enums?
Enums, short for enumerations, are a data type that consists of a set of named constants. They are used to represent a fixed set of values, such as days of the week or colors.
Why should I use enums instead of integers or strings?
Enums provide type safety and improve code readability. They prevent errors by restricting variables to a predefined set of values and make your code easier to understand and maintain.
How do I convert a string to an enum value?
Use the language-specific methods like valueOf() in Java or Enum.Parse()/Enum.TryParse() in C. Always handle potential exceptions or errors when the string doesn't match any enum value.
How do I convert an integer to an enum value?
Use the language-specific methods like casting in Java or Enum.ToObject() in C. Ensure you validate the integer value to be within the valid range of the enum before converting.
By understanding how to get enum value by string or int, you empower yourself to write cleaner, more robust, and easier-to-maintain code. Remember that careful validation and error handling are your best allies in preventing unexpected issues. Knowing the specific methods and best practices of your chosen language will further enhance your ability to effectively work with enums.

Now that you’re equipped with the knowledge to handle enum conversions effectively, consider exploring other advanced enum techniques, such as adding custom methods or implementing interfaces. These techniques can further enhance the functionality and flexibility of your enums, allowing you to create even more powerful and expressive code. Take the time to practice these concepts in your own projects, and you’ll soon become proficient in working with enums. For more information on improving your code quality, check out our guide to code optimization.

Question & Answer :
How can I get the enum value if I have the enum string or enum int value. eg: If i have an enum as follows:

public enum TestEnum { Value1 = 1, Value2 = 2, Value3 = 3 } 

and in some string variable I have the value “value1” as follows:

string str = "Value1" 

or in some int variable I have the value 2 like

int a = 2; 

how can I get the instance of enum ? I want a generic method where I can provide the enum and my input string or int value to get the enum instance.

No, you don’t want a generic method. This is much easier:

MyEnum myEnum = (MyEnum)myInt; MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString); 

I think it will also be faster.