To get the string value of an enum in C#, use the built-in Enum.GetName() method or the ToString() method. For example, Enum.GetName(typeof(Color), Color.Red) returns "Red". This article explains four reliable ways to retrieve enum string values, including handling custom string attributes, and covers common pitfalls like performance and missing values.
Understanding Enums in C#
An enum (short for enumeration) is a value type that defines a set of named constants, each with an underlying integer value. By default, the underlying type is int, and the values start at 0 and increment by 1 unless you assign them explicitly. For example:
enum Color { Red, Green, Blue }
Here, Red is 0, Green is 1, and Blue is 2. Enums are commonly used to make code more readable and to restrict a variable to a set of predefined values. When you need to display or store the name of an enum value as a string—for logging, serialization, or user interfaces—you need to convert it.
Method 1: Using ToString()
The simplest way to get the string name of an enum value is to call the ToString() method on the enum instance. Every enum type inherits from System.Enum, which overrides ToString() to return the name of the constant.
Color c = Color.Green;
string name = c.ToString(); // "Green"
This works for any enum value, but if the enum has a [Flags] attribute and the value is a combination of multiple flags, ToString() returns a comma-separated list of the flag names (e.g., "Red, Blue"). For a single flag, it returns just that name. This method is straightforward and requires no extra code, but it is not the fastest option if called in a tight loop because it uses reflection internally.
Method 2: Using Enum.GetName()
The Enum.GetName(Type, object) static method returns the name of the constant that has the specified value. It takes two parameters: the enum type and the value (as an object).
string name = Enum.GetName(typeof(Color), Color.Blue); // "Blue"
You can also pass the underlying integer value directly, which is useful when you have a numeric value from a database or user input:
string name = Enum.GetName(typeof(Color), 2); // "Blue"
If the value does not correspond to a defined enum member, Enum.GetName() returns null. This is a key difference from ToString(), which would return the numeric string (e.g., "5") for an undefined value. In terms of performance, Enum.GetName() is slightly faster than ToString() because it avoids the virtual call overhead, but both use reflection internally.
Method 3: Using Enum.GetNames() and Enum.GetValues()
If you need to get all string names of an enum type, or you want to map a value to a name without calling a method each time, you can use Enum.GetNames() and Enum.GetValues() to build a lookup dictionary once and reuse it.
// Build a dictionary once (e.g., in a static constructor)
var nameByValue = new Dictionary<Color, string>();
foreach (Color value in Enum.GetValues(typeof(Color)))
{
nameByValue[value] = value.ToString();
}
// Later, get the string quickly
string name = nameByValue[Color.Red]; // "Red"
This approach is the most efficient if you are converting many enum values in a performance-critical section, because it avoids repeated reflection calls. However, it requires extra memory and setup code. A simpler one-liner using LINQ is also possible, but it still enumerates all values each time unless you cache the result.
Method 4: Using Custom Attributes for Different String Values
Sometimes the enum member name is not what you want to display. For example, you might want NotAvailable to show as "N/A" or InProgress as "In Progress". In such cases, you can decorate each enum member with a custom attribute, such as [Description] from System.ComponentModel, and write a helper method to retrieve it.
using System.ComponentModel;
enum Status
{
[Description("Not Available")]
NotAvailable,
[Description("In Progress")]
InProgress,
[Description("Completed")]
Completed
}
public static string GetDescription(Enum value)
{
var field = value.GetType().GetField(value.ToString());
var attr = field.GetCustomAttribute<DescriptionAttribute>();
return attr != null ? attr.Description : value.ToString();
}
// Usage
string status = GetDescription(Status.InProgress); // "In Progress"
This method uses reflection to read the attribute, so it is slower than the previous methods. For better performance, you can cache the results in a dictionary. Also, note that the DescriptionAttribute is part of System.ComponentModel and is commonly used in UI frameworks like ASP.NET MVC and WPF.
Common Pitfalls and Misconceptions
One common mistake is assuming that ToString() always returns the enum name. For an undefined value (e.g., (Color)5), ToString() returns the numeric string, not a name. This can cause bugs when you later try to parse it back. Always validate that the value is defined using Enum.IsDefined() if you are dealing with user input.
Another misconception is that Enum.GetName() throws an exception for undefined values—it does not; it returns null. This can lead to NullReferenceException if you don’t check for null.
Performance is another area of confusion. Both ToString() and Enum.GetName() are relatively slow because they use reflection. In high-frequency loops (e.g., logging thousands of messages), this can be a bottleneck. The dictionary approach or precomputed arrays are much faster.
How to Choose the Right Approach
Choosing the right method depends on your specific needs:
- Simplicity: Use
ToString()for occasional conversions where performance is not critical. - Null safety: Use
Enum.GetName()when you need to handle undefined values gracefully (returnsnull). - Performance: Use a pre-built dictionary or array if you convert many values repeatedly.
- Custom display strings: Use a custom attribute with a helper method, and cache the results for performance.
For most applications, ToString() is perfectly fine. Only optimize when profiling shows it is a bottleneck.
Frequently Asked Questions
How do I get the enum string value from an integer?
Use Enum.GetName(typeof(MyEnum), myInt). If the integer is not a defined enum value, it returns null. Alternatively, cast the integer to the enum type and call ToString(), but that would return the numeric string for undefined values.
What is the difference between ToString() and Enum.GetName()?
Both return the name of the enum constant for defined values. The difference is that ToString() is an instance method that also handles flags combinations, while Enum.GetName() is a static method that returns null for undefined values. Performance is similar, but Enum.GetName() is slightly faster.
Can I use nameof() to get the enum string?
Yes, you can use nameof(Color.Red), which returns "Red". However, nameof requires a compile-time constant expression, so you cannot use it with a variable enum value. It is useful when you know the member at compile time.
How do I get the string for a flags enum combination?
For a [Flags] enum, ToString() returns a comma-separated list of the set flags (e.g., "Red, Blue"). Enum.GetName() will only return a name if the value exactly matches a single defined member; otherwise it returns null. To get a custom format, you might need to parse the flags manually.
Is there a built-in way to get a string with spaces?
No, the built-in methods return the exact member name. To get a string with spaces or other formatting, you need to use a custom attribute or a switch statement. The DescriptionAttribute approach is common.
Conclusion
Getting the string value of an enum is a common task in C#. The simplest solution is ToString(), but for more control and better performance, use Enum.GetName() or a cached dictionary. For custom display strings, use a custom attribute. Always be mindful of undefined values and performance in hot paths. With these techniques, you can handle any enum-to-string conversion requirement in your applications.
Related
- Generate Random Numbers in a Range: 6 Easy Ways
- String Coding Questions in Java: A Practical Guide
- Button Cell Battery Charger: How It Works & What to Know
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Normalize Text: Clean Data FastTo normalize text in Excel, use the TRIM function to remove extra spaces, UPPER, LOWER, or PROPER to…
- Name Badge Template in Word: Create One Step by StepCreate a reusable name badge template in Word by setting up a page and sizing a table to…
- How to Use ENUM in SQL: A Practical GuideENUM is a string object in SQL that lets you define a column with a fixed set of…
- Add a Print Area in Excel: Setup, Options, and FixesTo add a print area in Excel for Microsoft 365 on Windows, select the cells you want to…
- Vacation Budget Spreadsheet: Plan Costs and Track SpendingA vacation budget spreadsheet helps you estimate trip costs before booking, then compare those estimates with what you…
- How to Set Enum Value in Java (with Code Examples)In Java, an enum is a special class that represents a fixed set of constants. Setting an enum…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.