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.
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.
enum EnumName
{
Value1,
Value2,
Value3
}
Each member inside the enum is assigned an integer value automatically starting from 0.
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.
When you define an enumeration in C#, the compiler internally assigns numeric values to each member. By default:
However, you can explicitly assign values.
enum Status
{
Pending = 1,
Approved = 5,
Rejected = 10
}
In this example:
This flexibility makes C# enum with values very powerful for business logic.
By default, the underlying type of a C# Enum is int. However, you can change it to:
enum ErrorCode : byte
{
None = 0,
Minor = 1,
Major = 2,
Critical = 3
}
This reduces memory usage when working with large datasets.
Using enumeration in C# provides several advantages:
Instead of writing:
if(status == 1)
You write:
if(status == Status.Pending)
Enum variables can only hold defined values. This prevents accidental assignment of invalid numbers.
If values change, you update them in one place.
Modern IDEs like Visual Studio provide suggestions for enum members.
Status s = Status.Approved;
int value = (int)s;
Console.WriteLine(value);
Output: 5
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.
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.
Sometimes you need to combine multiple enum values. In such cases, use Flags enum in C#.
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.
The Enum class provides built-in methods:
string[] names = Enum.GetNames(typeof(Status));
foreach(string name in names)
{
Console.WriteLine(name);
}
Array values = Enum.GetValues(typeof(Status));
foreach(var val in values)
{
Console.WriteLine(val);
}
Status s = (Status)Enum.Parse(typeof(Status), "Approved");
Console.WriteLine(s);
Status result;
bool success = Enum.TryParse("Rejected", out result);
if(success)
{
Console.WriteLine(result);
}
Using C# enum methods makes dynamic handling of enumerations easier.
Both enums and constants define fixed values, but enums:
Constants are better for independent fixed values, while enums are ideal for related sets.
Enums are widely used in:
Status? currentStatus = null;
class Order
{
public Status OrderStatus { get; set; }
}
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.
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.
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.
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.
Copyrights © 2024 letsupdateskills All rights reserved