Structs and Enums

Back

Loading concept...

Structs and Enums: Building Blocks of C# 🏗️

The Big Picture: Boxes and Labels

Imagine you have a toy box where you keep all your action figures together. That’s what a Struct is—a container that groups related things. Now imagine you have labels for your toys: “Robot,” “Dinosaur,” “Superhero.” That’s what an Enum is—a set of named choices.

Let’s explore these powerful C# building blocks!


đź§± What is a Struct?

A struct (short for “structure”) is like a lunchbox with different compartments. Each compartment holds something specific—a sandwich, an apple, a juice box. Together, they make one complete lunch!

Simple Example

struct Point
{
    public int X;
    public int Y;
}

// Using it
Point p;
p.X = 10;
p.Y = 20;

Here, Point groups two numbers (X and Y) together. Instead of carrying two separate numbers everywhere, you carry one neat package!

Real-Life Analogy

Think of an envelope ✉️:

  • It has a sender address (one piece of data)
  • It has a receiver address (another piece of data)
  • Together, they form ONE envelope
struct Envelope
{
    public string SenderAddress;
    public string ReceiverAddress;
}

đź”’ Readonly Structs

Sometimes you want your lunchbox to be sealed—once you pack it, nobody can change what’s inside. That’s a readonly struct!

Why Use Readonly Structs?

  1. Safety: No accidental changes
  2. Speed: C# can optimize them better
  3. Trust: Other programmers know it won’t change

Example

readonly struct Temperature
{
    public readonly double Celsius;

    public Temperature(double celsius)
    {
        Celsius = celsius;
    }

    public double ToFahrenheit()
        => Celsius * 9/5 + 32;
}

Once you create a Temperature, the value is locked forever. Like carving your name in stone! 🪨


📦 Value Types vs Reference Types

This is super important! Let’s use a story.

The Photocopy Machine Story

Value Types (like structs) are like photocopies:

  • When you give someone a photocopy, they get their OWN copy
  • If they draw on it, YOUR original is safe
  • Each person has their own separate paper

Reference Types (like classes) are like sharing a Google Doc:

  • Everyone looks at the SAME document
  • If someone edits it, EVERYONE sees the change
  • There’s only ONE document, shared by all

See It in Code

// VALUE TYPE (struct)
struct Box { public int Size; }

Box box1;
box1.Size = 10;
Box box2 = box1;     // Makes a COPY!
box2.Size = 99;      // Only box2 changes

// box1.Size is still 10!
// box2.Size is 99
// REFERENCE TYPE (class)
class Balloon { public int Size; }

Balloon b1 = new Balloon();
b1.Size = 10;
Balloon b2 = b1;     // Points to SAME balloon!
b2.Size = 99;        // Both change!

// b1.Size is 99
// b2.Size is 99

Quick Comparison

graph TD A["Value Type"] --> B["Gets Copied"] A --> C["Independent"] A --> D["Like Photocopies"] E["Reference Type"] --> F["Gets Shared"] E --> G["Connected"] E --> H["Like Google Docs"]

🗄️ Stack vs Heap Memory

Where does your data live? There are two neighborhoods: Stack and Heap.

The Stack: Fast Food Counter 🍔

  • Super fast service
  • Small orders only
  • Automatic cleanup when you leave
  • Value types live here!

The Heap: Restaurant Table 🍽️

  • Takes longer to get seated
  • Large parties welcome
  • You must ask for the bill (cleanup)
  • Reference types live here!

Visual Guide

graph TD S["STACK Memory"] S --> S1["Fast access"] S --> S2["Fixed size"] S --> S3["Auto cleanup"] S --> S4["Value types"] H["HEAP Memory"] H --> H1["Flexible size"] H --> H2["Slower access"] H --> H3["Manual cleanup"] H --> H4["Reference types"]

Example in Action

void Example()
{
    int age = 25;        // Stack - quick!
    Point p;             // Stack - struct
    p.X = 5; p.Y = 10;

    string name = "Bob"; // Heap - reference
    int[] nums = {1,2};  // Heap - array
}
// When function ends, Stack cleans up
// Heap waits for garbage collector

Why Does This Matter?

Stack Heap
Faster Slower
Limited size Bigger capacity
Auto cleanup GC cleanup
Local variables Objects/Arrays

🏷️ Enums: Named Choices

An Enum (short for “enumeration”) is a list of named options. Instead of remembering that 1 means Monday and 2 means Tuesday, you just say Day.Monday!

The Traffic Light Example 🚦

enum TrafficLight
{
    Red,    // 0
    Yellow, // 1
    Green   // 2
}

// Using it
TrafficLight signal = TrafficLight.Red;

if (signal == TrafficLight.Red)
{
    Console.WriteLine("Stop!");
}

Why Enums Rock

  1. Readable: Status.Active beats remembering 1
  2. Safe: Can’t accidentally use Status.Banana
  3. Autocomplete: Your editor suggests valid options!

Setting Custom Values

enum HttpStatus
{
    OK = 200,
    NotFound = 404,
    ServerError = 500
}

int code = (int)HttpStatus.NotFound;
// code = 404

Days of the Week Example

enum DayOfWeek
{
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6
}

DayOfWeek today = DayOfWeek.Friday;
Console.WriteLine(quot;Today is {today}");
// Prints: Today is Friday

🎯 When to Use What?

Use a Struct When:

  • Data is small (like a Point with X, Y)
  • You want independent copies
  • You need speed over flexibility

Use a Class When:

  • Data is large or complex
  • You want shared references
  • You need inheritance

Use an Enum When:

  • You have a fixed set of options
  • Values won’t change after writing code
  • You want readable, safe code

đź’ˇ Key Takeaways

graph TD A["Structs & Enums"] --> B["Struct"] A --> C["Enum"] B --> B1["Groups data together"] B --> B2["Value type - copied"] B --> B3["Lives on Stack"] B --> B4["readonly = locked"] C --> C1["Named choices"] C --> C2["Replaces magic numbers"] C --> C3["Type-safe options"]

🎬 Summary Story

Imagine you’re organizing a birthday party 🎂:

  1. Struct = The party invitation card

    • Has: Name, Date, Location (grouped together)
    • When you copy it, each friend gets their OWN card
  2. Readonly Struct = A printed poster

    • Once printed, you can’t change the date!
  3. Value vs Reference =

    • Value: Giving everyone a cupcake (each person has their own)
    • Reference: Sharing one big cake (everyone eats from the same cake)
  4. Stack vs Heap =

    • Stack: Party favors on the table (quick to grab, limited space)
    • Heap: Big gifts in the other room (more space, takes time to fetch)
  5. Enum = The party theme choices

    • Theme.Pirates, Theme.Dinosaurs, Theme.Space
    • Clear, fixed options everyone understands!

Now you understand the building blocks of C# data organization! Structs keep data together, readonly structs lock it tight, value types copy while reference types share, stack is fast but small, heap is big but slower, and enums give us clean choices. You’ve got this! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.