Structures and Enums in C#

Introduction

In C#, structures (struct) are value types that allow you to create data types that can hold multiple related variables. Enums (enumerations) represent a set of named constants, making your code more readable and easier to maintain.

Structures in C#

A struct in C# is a value type that allows you to bundle multiple related variables into a single unit. Structs are typically used to represent small, lightweight objects that do not require inheritance.

Example: Defining and Using a Struct

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void Display()
    {
        Console.WriteLine($"Point({X}, {Y})");
    }
}

Point p = new Point(5, 10);
p.Display();  // Output: Point(5, 10)
        

In this example, the Point struct defines two fields, X and Y. The struct also includes a constructor and a method to display the point's coordinates.

Enums in C#

An enum in C# is a distinct type that consists of a set of named constants. Enums are useful when you need to work with a set of fixed values.

Example: Defining and Using an Enum

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

DayOfWeek today = DayOfWeek.Monday;
Console.WriteLine(today);  // Output: Monday
        

In this example, the DayOfWeek enum defines constants representing the days of the week. The today variable is assigned the value DayOfWeek.Monday, and it prints the day.

Using Enums with Switch Statements

Enums can be used with switch statements to perform different actions based on the enum value.

Example: Enum with Switch Statement

DayOfWeek today = DayOfWeek.Wednesday;

switch (today)
{
    case DayOfWeek.Monday:
        Console.WriteLine("It's Monday.");
        break;
    case DayOfWeek.Wednesday:
        Console.WriteLine("It's Wednesday.");
        break;
    case DayOfWeek.Friday:
        Console.WriteLine("It's Friday.");
        break;
    default:
        Console.WriteLine("It's another day.");
        break;
}
        

In this example, a switch statement is used to perform different actions based on the value of the today enum.

Key Points to Remember

  • Structures (struct) are value types used to group related variables into a single unit.
  • Enums (enum) represent a set of named constants, improving code readability and maintainability.
  • Structs are typically used for small, lightweight objects that do not require inheritance, while enums are useful when working with a set of fixed values.
  • Enums can be used with switch statements to execute different actions based on the enum value.