- 🔧 By default, C# enums return their name as a string, not their numeric value, which may be problematic in logs and APIs.
- 📊 Casting an enum to an int is the most efficient way to print enum as integer in C#.
- 🛑 You cannot globally override the enum default format—manual casting or helper methods are required.
- 📦 JSON serializers like Newtonsoft and System.Text.Json serialize enums as names unless explicitly configured to output numbers.
- 💡 Using enums in SQL queries is safest when passing numeric values for long-term stability and localization safety.
Why Enum Formatting Matters in C#
C# enums make code clean, safe, and clear. But their default behavior can cause problems when you debug, store data, use APIs, or check logs. By default, C# shows enum names, not their numbers. This can make logs hard to read, make data files bigger, or show too much internal detail in JSON APIs. If you've ever asked how to change a C# enum to a number, or why "Active" appears in your API instead of 1, then this guide explains what you need to know.
What is an Enum in C#?
In C#, an enum (short for "enumeration") is a value type. It sets up a list of named constants. Enums give names to numbers. This makes code clearer and better organized. Use enums when a variable can only have one value from a small, known list.
Here’s a simple enum in C#:
public enum Status
{
Inactive = 0,
Active = 1,
Deleted = 2
}
When you use Status.Active, you are talking about the number 1 in your program. It is easier to read and safer.
Key Features:
- Enums use numbers (
intby default). - They give meaning to numbers.
- They stop bad values from being used when you write code.
- They make switch-case statements easier to read.
If you don’t assign values explicitly, enums start at 0 and increment by 1 automatically:
public enum Mode
{
Off, // 0
On, // 1
Standby // 2
}
Default Enum Output: String vs. Integer
When you use Console.WriteLine() or JSON serialize an enum in C#, the string name appears by default, not the numeric value:
Console.WriteLine(Status.Active);
// Output: "Active"
Console.WriteLine(Status.Deleted.ToString());
// Output: "Deleted"
This happens because .ToString() normally returns the constant's name. This helps developers debug. But it might not be right when working with databases, other systems, or when you want smaller data files.
This formatting issue becomes more problematic when:
- You log many details in places where speed matters.
- You send data in APIs that expect numbers.
- You write system logs for rules, backups, or analysis.
How to Print an Enum as a Number
Converting a C# enum to its numeric value is simple and fully supported via casting. Here’s how to do it:
Explicit Cast:
int value = (int)Status.Active;
Console.WriteLine(value);
// Output: 1
Inline Casting:
Console.WriteLine((int)Status.Deleted);
// Output: 2
This is the best and fastest way to print an enum as a number. It is a quick memory check inside, with no complex steps.
Bonus: Cast to long, byte, or other numeric types
If you’re using an enum with a different underlying type, such as byte or long, you'll need to cast accordingly:
enum SmallEnum : byte
{
One = 1,
Two = 2
}
Console.WriteLine((byte)SmallEnum.Two);
// Output: 2
Casting lets you choose how the output looks. It costs nothing in terms of speed, even in systems that need to be fast.
Can You Change the Enum Default Format Globally?
One of the most common developer questions is: Can I override .ToString() on an enum to return its numeric value by default?
Sadly, no.
C# enums are sealed types. This means you cannot change how .ToString() works for them. Enum types come from System.Enum, so you cannot use different ways to change their behavior everywhere.
So, everywhere you want a number, you must cast it to a number. This is done on purpose for clear design. But it means you need to be careful in big projects.
Workarounds and Cleaner Numeric Enum Patterns
You cannot change the default behavior. But you can use helper methods to make sure enum formatting is the same and easy to read throughout your code.
Option 1: Enum Extension Method
Create a reusable method to convert enums into their numeric equivalent.
public static class EnumExtensions
{
public static int GetNumericValue(this Enum value)
{
return Convert.ToInt32(value);
}
}
Usage:
Console.WriteLine(Status.Deleted.GetNumericValue());
// Output: 2
This keeps your main code cleaner. You do not need to cast many times. It works well in shared tools for large companies.
Option 2: Centralized Logger or Formatter
You can put all enum formatting logic into one logging service or data changer class:
public static class EnumFormatter
{
public static string FormatEnumValue(Enum value, bool asNumeric = false)
{
return asNumeric ? Convert.ToInt32(value).ToString() : value.ToString();
}
}
This way, you can switch between string or number formats. It depends on where the output goes, like an API answer or internal logs.
Serializing Enums as Numbers in JSON
When you share data as JSON, you must pick if enums show up as text or numbers. Bad choices can cause:
- Problems with strict API rules.
- Showing too much about internal enum names.
- Big data files because of long strings.
Newtonsoft.Json (Json.NET)
If you're using the popular library Newtonsoft.Json (a.k.a. Json.NET), enums are serialized as strings by default.
To serialize as numbers:
JsonConvert.SerializeObject(Status.Active);
// Output: "Active"
JsonConvert.SerializeObject(Status.Active, new JsonSerializerSettings
{
Converters = new List<JsonConverter>(),
Formatting = Formatting.None
});
// Output: 1
To completely avoid serialization as strings, don't supply StringEnumConverter.
From Newtonsoft documentation: Serialize enum as integer
System.Text.Json (.NET Core 3.0+)
Microsoft's built-in System.Text.Json also defaults to serializing enums as numbers unless you specify a string converter.
using System.Text.Json;
using System.Text.Json.Serialization;
var status = Status.Active;
// Serialize with strings
var stringOptions = new JsonSerializerOptions
{
Converters = { new JsonStringEnumConverter() }
};
Console.WriteLine(JsonSerializer.Serialize(status, stringOptions));
// Output: "Active"
// Serialize as number (default behavior)
var defaultOptions = new JsonSerializerOptions();
Console.WriteLine(JsonSerializer.Serialize(status, defaultOptions));
// Output: 1
This makes System.Text.Json easier to use when you want clear number output. This is good for APIs and small IoT programs.
Using Enums Safely in SQL Queries
When you work with SQL databases, using enum names can make your database structure weak. It can also cause issues with different languages or when you change your system.
Risky:
SELECT * FROM Users WHERE Status = 'Deleted';
Recommended:
SELECT * FROM Users WHERE Status = 2;
Why this matters:
- Enum names might change if you update your code or language settings.
- Making sure numbers are always used means you do not depend on names shown on screen.
- Numbers match database column types (
tinyint,int).
For systems that send enum values to databases, cast them to (int). Or, store the numbers directly using ORM settings.
Reference: RedHat. (2021). Programming Best Practices for Safer Systems.
Flags and Bitwise Enums: Extra Caution Needed
C# supports [Flags] enums for combining multiple values using bitwise operations:
[Flags]
public enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
Admin = Read | Write | Execute
}
Assigning combinations:
Permissions combined = Permissions.Read | Permissions.Write;
Console.WriteLine(combined);
// Output: Read, Write
Console.WriteLine((int)combined);
// Output: 3
Use cases:
- Who can do what (roles).
- Turning options on or off.
- Settings.
But when logging or saving data, how you read these values is important. A 3 might make sense to a computer. But it may not make sense to a person or a data checker. Always write down and format these values clearly if other people or systems rely on them.
Enum Display Attributes (But Not for Numbers)
C# allows you to add metadata to enums using attributes like [Description], [Display(Name ="...")], or [Obsolete].
public enum Status
{
[Description("User is active")]
Active = 1
}
To retrieve descriptions:
public static string GetDescription(Enum value)
{
var field = value.GetType().GetField(value.ToString());
var attribute = field?.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
return attribute?.Description ?? value.ToString();
}
This is good for labels on screen, form tools, and small pop-up texts. But it is not for making enums show as numbers.
Enums in Logging and Debugging
Logging plans that are clear and always the same often use enums. The best ways to do this are:
- Use
.ToString()for logs people will read. - Use
(int)to cast for numbers, system data, or moving data. - Log both when you need to.
Example:
Console.WriteLine($"User status: {status} ({(int)status})");
// Output: User status: Active (1)
This makes it clear when you quickly check problems or watch your app.
Performance of Printing Enum as Integer
Casting an enum to int is very fast. It uses no computer resources.
However, calling .ToString():
- It looks up a virtual method.
- It puts a string on the memory heap.
- It can make garbage collection work harder in fast loops.
For high-throughput systems:
- Use numbers in logs or when moving data.
- Do not make extra strings in parts of your code that need to be fast.
Quick benchmark:
(int)enum: ~0 allocationsenum.ToString(): ≥1 allocation per call
Best Practices for Using Enums as Numbers
To format enums well, you need to balance how you write code, what your system needs, and how easy your code is to keep working.
✅ Do:
- Always set values, like
Active = 1, to stop numbers from changing by mistake. - Use helper methods, not just casts in the code.
- Save as numbers when working with other systems.
- Use a default member, like
Unknown = 0, for safer reading of data.
❌ Don't:
- Do not depend on string names in SQL or database plans.
- Do not think names will stay the same forever.
- Do not translate enum names without a plan for different languages.
- Do not use
[Flags]too much for simple things.
Should You Use an Enum at All?
While enums are powerful, they are not a one-size-fits-all solution.
Consider alternatives when:
- Values change too often (for example, settings that keep changing).
- You need names in many different languages.
- You need a lot of extra information or special actions for each "enum."
Alternatives to Enums:
- Classes with constants (like
public const int Active = 1). - Dictionaries to match values to labels while the program runs.
- A safe enum method (objects that have actions and extra information).
But for data that stays the same, has a clear end, and is often used, enums are still the best.
Know Your Tools, Improve Your Output
C# enums are not just for looks. They are key parts of making code clean and safe. Knowing how to control their output, from logs to APIs and databases, can save time, fix fewer bugs, and make systems work better.
To recap:
- Cast C# enums to numbers.
- Use extension methods to make formatting the same.
- Use settings or libraries to control how you save data.
- Log well and do not show too much info about enums in your public code.
And when code talks to both computers and people, how you format it is more important than you might think.
Citations
- Microsoft. (n.d.). Enum (C# Reference). Retrieved from https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum
- Newtonsoft. (n.d.). Json.NET Documentation. Retrieved from https://www.newtonsoft.com/json/help/html/SerializeEnumAsInteger.htm
- RedHat. (2021). Programming Best Practices for Safer Systems.