Structures and Enums in C#

What are Structures and Enums?

In C#, Structures (structs) and Enumerations (enums) are value types that help define custom data structures and fixed sets of named constants, respectively.

Structures in C#

A struct in C# is similar to a class but is a value type instead of a reference type. Structs are often used for small, lightweight objects that do not require inheritance.

Example of a Structure:

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})");
    }
}

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

In this example, Point is a struct that contains integer fields X and Y. It also has a constructor and a method to display the values.

Key Features of Structures

  • Structures are value types and stored on the stack.
  • They do not support inheritance but can implement interfaces.
  • Useful for representing lightweight objects.
  • Do not require explicit constructors.

Enumerations in C#

An enum is a distinct type that consists of a set of named constants. It is used to define a collection of related values.

Example of an Enum:

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

// Usage
DaysOfWeek today = DaysOfWeek.Wednesday;
Console.WriteLine($"Today is: {today}");  // Output: Today is: Wednesday
        

In this example, DaysOfWeek is an enum that represents the days of the week, making the code more readable and maintainable.

Key Features of Enums

  • Enums provide a way to define named integral constants.
  • By default, the first enum member starts at index 0 and increments by 1.
  • You can explicitly set values to enum members.
  • Enums improve code readability by using meaningful names instead of numbers.

Differences Between Structures and Enums

Feature Structures (struct) Enumerations (enum)
Type Value Type Value Type
Purpose Represents a lightweight data structure Represents a fixed set of named constants
Inheritance Cannot inherit from a class, but can implement interfaces Cannot inherit or implement interfaces
Storage Stored on the stack Stored on the stack
Members Can have fields, properties, methods, and constructors Only contains named constants

Key Points to Remember

  • Structures are value types that can hold multiple fields and methods.
  • Enums are used to define named constant values, improving readability.
  • Structures do not support inheritance but can implement interfaces.
  • Enums are best suited for representing fixed sets of related constants.