0
0
C Sharp (C#)programming~5 mins

Enum vs constants decision in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Enums and constants both store fixed values, but enums group related values with names, while constants hold single fixed values. Choosing between them helps keep code clear and easy to change.

When you have a set of related named values like days of the week or colors.
When you want to make code easier to read by using meaningful names instead of numbers or strings.
When you need to restrict a variable to a limited set of options.
When you want to avoid magic numbers or strings scattered in your code.
When you have a single fixed value that won't change and is used in many places.
Syntax
C Sharp (C#)
enum EnumName
{
    Value1,
    Value2,
    Value3
}

const dataType ConstantName = value;

Enums define a group of named values under one type.

Constants define a single fixed value with a name.

Examples
This enum groups days of the week as named values.
C Sharp (C#)
enum Day
{
    Sunday,
    Monday,
    Tuesday
}
This constant holds a fixed number for maximum users allowed.
C Sharp (C#)
const int MaxUsers = 100;
Enum with explicit numeric values assigned to each name.
C Sharp (C#)
enum Color
{
    Red = 1,
    Green = 2,
    Blue = 3
}
Constant string value for application name.
C Sharp (C#)
const string AppName = "MyApp";
Sample Program

This program shows how to use an enum to represent status values and a constant for a fixed number. It prints both to the console.

C Sharp (C#)
using System;

class Program
{
    enum Status
    {
        Pending,
        Approved,
        Rejected
    }

    const int MaxAttempts = 3;

    static void Main()
    {
        Status currentStatus = Status.Pending;
        Console.WriteLine($"Current status: {currentStatus}");
        Console.WriteLine($"Max attempts allowed: {MaxAttempts}");
    }
}
OutputSuccess
Important Notes

Use enums when you have multiple related options to choose from.

Use constants for single fixed values that do not change.

Enums improve code readability and reduce errors by limiting possible values.

Summary

Enums group related named values under one type.

Constants hold single fixed values with a name.

Choose enums for sets of options, constants for single fixed values.