C# - Enum

C# Enum in Depth 

Introduction to C# Enum

In C# programming, an Enum in C# (short for enumeration) is a powerful value type that allows developers to define a set of named constants. Enums improve code readability, maintainability, and type safety. Instead of using numeric literals such as 0, 1, or 2 in your program, you can assign meaningful names to those values using enumeration in C#.

If you are learning C# basics, understanding the C# Enum type is essential. Enums are widely used in real-world applications such as status codes, days of the week, user roles, order states, and configuration options.

What is Enum in C#?

An Enum in C# is a special data type that allows a variable to be one of a predefined set of constants. These constants are defined using the enum keyword in C#. By default, the underlying type of an enum is int.

Enums are useful when you have a fixed set of related values that should not change during program execution.

Basic Syntax of Enum in C#


enum EnumName
{
    Value1,
    Value2,
    Value3
}

Each member inside the enum is assigned an integer value automatically starting from 0.

Simple Enum Example in C#


using System;

enum Days
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

class Program
{
    static void Main()
    {
        Days today = Days.Wednesday;
        Console.WriteLine(today);
    }
}

Output: Wednesday

Here, Sunday = 0, Monday = 1, Tuesday = 2, and so on.

How Enum Works Internally

When you define an enumeration in C#, the compiler internally assigns numeric values to each member. By default:

  • First member = 0
  • Next member increments by 1

However, you can explicitly assign values.

Enum with Custom Values


enum Status
{
    Pending = 1,
    Approved = 5,
    Rejected = 10
}

In this example:

  • Pending = 1
  • Approved = 5
  • Rejected = 10

This flexibility makes C# enum with values very powerful for business logic.

Underlying Type of Enum in C#

By default, the underlying type of a C# Enum is int. However, you can change it to:

  • byte
  • sbyte
  • short
  • ushort
  • int
  • uint
  • long
  • ulong

Enum with Different Underlying Type


enum ErrorCode : byte
{
    None = 0,
    Minor = 1,
    Major = 2,
    Critical = 3
}

This reduces memory usage when working with large datasets.

Why Use Enum in C# Programming?

Using enumeration in C# provides several advantages:

1. Improves Code Readability

Instead of writing:


if(status == 1)

You write:


if(status == Status.Pending)

2. Type Safety

Enum variables can only hold defined values. This prevents accidental assignment of invalid numbers.

3. Easy Maintenance

If values change, you update them in one place.

4. Better IntelliSense Support

Modern IDEs like Visual Studio provide suggestions for enum members.

Enum Casting in C#

Implicit Casting to Integer


Status s = Status.Approved;
int value = (int)s;
Console.WriteLine(value);

Output: 5

Explicit Casting from Integer


int number = 10;
Status s = (Status)number;
Console.WriteLine(s);

Output: Rejected

Be careful when casting from integers. If the number does not match any defined enum value, it will still compile but may cause logical errors.

Enum and Switch Statement in C#

Enums are commonly used with switch statements in C# programming.


Status orderStatus = Status.Pending;

switch(orderStatus)
{
    case Status.Pending:
        Console.WriteLine("Order is pending.");
        break;

    case Status.Approved:
        Console.WriteLine("Order approved.");
        break;

    case Status.Rejected:
        Console.WriteLine("Order rejected.");
        break;
}

This approach improves clarity and eliminates magic numbers.

Flags Enum in C#

Sometimes you need to combine multiple enum values. In such cases, use Flags enum in C#.

Using Flags Attribute


using System;

[Flags]
enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4
}

class Program
{
    static void Main()
    {
        Permissions userPermission = Permissions.Read | Permissions.Write;
        Console.WriteLine(userPermission);
    }
}

Output: Read, Write

Flags enums use bitwise operations to combine values.

Enum Methods in C#

The Enum class provides built-in methods:

1. Enum.GetNames()


string[] names = Enum.GetNames(typeof(Status));

foreach(string name in names)
{
    Console.WriteLine(name);
}

2. Enum.GetValues()


Array values = Enum.GetValues(typeof(Status));

foreach(var val in values)
{
    Console.WriteLine(val);
}

3. Enum.Parse()


Status s = (Status)Enum.Parse(typeof(Status), "Approved");
Console.WriteLine(s);

4. Enum.TryParse()


Status result;

bool success = Enum.TryParse("Rejected", out result);

if(success)
{
    Console.WriteLine(result);
}

Using C# enum methods makes dynamic handling of enumerations easier.

Enum vs Constants in C#

Both enums and constants define fixed values, but enums:

  • Provide better grouping
  • Improve readability
  • Offer type safety
  • Support switch-case directly

Constants are better for independent fixed values, while enums are ideal for related sets.

Real-World Applications of Enum in C#

Enums are widely used in:

  • Order management systems
  • User role management
  • Game development (states)
  • Configuration settings
  • API response status codes

Common Mistakes in C# Enum Usage

  • Assigning duplicate values unintentionally
  • Incorrect casting from integer
  • Not using Flags when combining values
  • Using enums for frequently changing values

Advanced Enum Concepts in C#

Nullable Enum


Status? currentStatus = null;

Enum in Classes


class Order
{
    public Status OrderStatus { get; set; }
}

Looping Through Enum


foreach(Status s in Enum.GetValues(typeof(Status)))
{
    Console.WriteLine(s);
}

The C# Enum is an essential feature of C# programming. It enhances readability, improves maintainability, ensures type safety, and simplifies logical conditions. Whether you are a beginner learning enumeration in C# or an experienced developer building enterprise applications, mastering enums will make your code cleaner and more professional.

By understanding enum example in C#, C# enum with values, Flags enum in C#, and C# enum methods, you can fully utilize this powerful feature in your applications.

logo

C#

Beginner 5 Hours

C# Enum in Depth 

Introduction to C# Enum

In C# programming, an Enum in C# (short for enumeration) is a powerful value type that allows developers to define a set of named constants. Enums improve code readability, maintainability, and type safety. Instead of using numeric literals such as 0, 1, or 2 in your program, you can assign meaningful names to those values using enumeration in C#.

If you are learning C# basics, understanding the C# Enum type is essential. Enums are widely used in real-world applications such as status codes, days of the week, user roles, order states, and configuration options.

What is Enum in C#?

An Enum in C# is a special data type that allows a variable to be one of a predefined set of constants. These constants are defined using the enum keyword in C#. By default, the underlying type of an enum is int.

Enums are useful when you have a fixed set of related values that should not change during program execution.

Basic Syntax of Enum in C#

enum EnumName { Value1, Value2, Value3 }

Each member inside the enum is assigned an integer value automatically starting from 0.

Simple Enum Example in C#

using System; enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } class Program { static void Main() { Days today = Days.Wednesday; Console.WriteLine(today); } }

Output: Wednesday

Here, Sunday = 0, Monday = 1, Tuesday = 2, and so on.

How Enum Works Internally

When you define an enumeration in C#, the compiler internally assigns numeric values to each member. By default:

  • First member = 0
  • Next member increments by 1

However, you can explicitly assign values.

Enum with Custom Values

enum Status { Pending = 1, Approved = 5, Rejected = 10 }

In this example:

  • Pending = 1
  • Approved = 5
  • Rejected = 10

This flexibility makes C# enum with values very powerful for business logic.

Underlying Type of Enum in C#

By default, the underlying type of a C# Enum is int. However, you can change it to:

  • byte
  • sbyte
  • short
  • ushort
  • int
  • uint
  • long
  • ulong

Enum with Different Underlying Type

enum ErrorCode : byte { None = 0, Minor = 1, Major = 2, Critical = 3 }

This reduces memory usage when working with large datasets.

Why Use Enum in C# Programming?

Using enumeration in C# provides several advantages:

1. Improves Code Readability

Instead of writing:

if(status == 1)

You write:

if(status == Status.Pending)

2. Type Safety

Enum variables can only hold defined values. This prevents accidental assignment of invalid numbers.

3. Easy Maintenance

If values change, you update them in one place.

4. Better IntelliSense Support

Modern IDEs like Visual Studio provide suggestions for enum members.

Enum Casting in C#

Implicit Casting to Integer

Status s = Status.Approved; int value = (int)s; Console.WriteLine(value);

Output: 5

Explicit Casting from Integer

int number = 10; Status s = (Status)number; Console.WriteLine(s);

Output: Rejected

Be careful when casting from integers. If the number does not match any defined enum value, it will still compile but may cause logical errors.

Enum and Switch Statement in C#

Enums are commonly used with switch statements in C# programming.

Status orderStatus = Status.Pending; switch(orderStatus) { case Status.Pending: Console.WriteLine("Order is pending."); break; case Status.Approved: Console.WriteLine("Order approved."); break; case Status.Rejected: Console.WriteLine("Order rejected."); break; }

This approach improves clarity and eliminates magic numbers.

Flags Enum in C#

Sometimes you need to combine multiple enum values. In such cases, use Flags enum in C#.

Using Flags Attribute

using System; [Flags] enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 } class Program { static void Main() { Permissions userPermission = Permissions.Read | Permissions.Write; Console.WriteLine(userPermission); } }

Output: Read, Write

Flags enums use bitwise operations to combine values.

Enum Methods in C#

The Enum class provides built-in methods:

1. Enum.GetNames()

string[] names = Enum.GetNames(typeof(Status)); foreach(string name in names) { Console.WriteLine(name); }

2. Enum.GetValues()

Array values = Enum.GetValues(typeof(Status)); foreach(var val in values) { Console.WriteLine(val); }

3. Enum.Parse()

Status s = (Status)Enum.Parse(typeof(Status), "Approved"); Console.WriteLine(s);

4. Enum.TryParse()

Status result; bool success = Enum.TryParse("Rejected", out result); if(success) { Console.WriteLine(result); }

Using C# enum methods makes dynamic handling of enumerations easier.

Enum vs Constants in C#

Both enums and constants define fixed values, but enums:

  • Provide better grouping
  • Improve readability
  • Offer type safety
  • Support switch-case directly

Constants are better for independent fixed values, while enums are ideal for related sets.

Real-World Applications of Enum in C#

Enums are widely used in:

  • Order management systems
  • User role management
  • Game development (states)
  • Configuration settings
  • API response status codes

Common Mistakes in C# Enum Usage

  • Assigning duplicate values unintentionally
  • Incorrect casting from integer
  • Not using Flags when combining values
  • Using enums for frequently changing values

Advanced Enum Concepts in C#

Nullable Enum

Status? currentStatus = null;

Enum in Classes

class Order { public Status OrderStatus { get; set; } }

Looping Through Enum

foreach(Status s in Enum.GetValues(typeof(Status))) { Console.WriteLine(s); }

The C# Enum is an essential feature of C# programming. It enhances readability, improves maintainability, ensures type safety, and simplifies logical conditions. Whether you are a beginner learning enumeration in C# or an experienced developer building enterprise applications, mastering enums will make your code cleaner and more professional.

By understanding enum example in C#, C# enum with values, Flags enum in C#, and C# enum methods, you can fully utilize this powerful feature in your applications.

Related Tutorials

Frequently Asked Questions for C#

C# is much easier to learn than C++. C# is a simpler, high-level-of-abstraction language, while C++ is a low-level language with a higher learning curve.

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Python and JavaScript programmers also earn high salaries, ranking #3 and #4 in compensation. 
C# is the highest-paid programming language but has less demand than Python, JavaScript, and Java.

No. Microsoft has invested substantially in ensuring that C# is the dominant language today, spending two billion dollars on marketing and attempting to convince developers to embrace this new platform, which is also based on the.NET foundation.

C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.


You can’t be able to become Master of C# in 3 months since it has many concepts to learn and implement. NOTE: no one can become master in particular programming language. Everyday they introducing new concepts we need to get practice on it which practically somewhat tough.

C-Sharp is one of the most widely used languages for creating system backend.It's because of its incredible features, such as Windows server automation. Apart from that, it's fantastic because it runs codes quite quickly. It can also be used to create CLI applications and game creation.

Easy to learn and use: C# is simpler than Java due to its use of fewer keywords and usually shorter lines of code. Hence, it is easier to learn to code in C# compared to Java. Flexible Data Types: C# provides more flexibility in defining data types than Java.

Four steps of code compilation in C# include : 
  • Source code compilation in managed code.
  • Newly created code is clubbed with assembly code.
  • The Common Language Runtime (CLR) is loaded.
  • Assembly execution is done through CLR.

The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.


The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.


Among other languages, C# is gaining huge popularity for developing web-based applications. Its core concepts help build an interactive environment and provide functionalities that the dynamic web platform requires. Most aspiring full-stack developers choose this versatile language.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270 and 20619) in 2003. Microsoft introduced C# along with .NET Framework and Visual Studio, both of which were closed-source. 

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Yes, C# is used by many large organizations, start-ups and beginners alike. It takes some of the useful features of C and adds syntax to save time and effort. Although C# is based on C, you can learn it without any knowledge of C β€” in fact, this course is perfect for those with no coding experience at all!

C# is a very mature language that evolved significantly over the years.
The C# language is one of the top 5 most popular programming languages and .NET is the most loved software development framework in the world.
TIOBE Index predicts C# as 2023 'Language of the Year' close to overtake Java in popularity.

Generally, the C# language is not limited to the Windows operating system. In a sense, however, it is limited to Microsoft software. C# language "belongs" to Microsoft, it is developed by Microsoft and it is Microsoft that provides the runtime environment required for the operation of programs written in C#.

C# (pronounced "C sharp") is called so because the "#" symbol is often referred to as "sharp." The name was chosen by Microsoft when they developed the language. It's a play on words related to musical notation where "C#" represents the musical note C sharp.

Dennis MacAlistair Ritchie (September 9, 1941 – c. October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B language.

C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.


line

Copyrights © 2024 letsupdateskills All rights reserved