SkillPilotAI

Struct and enum

A struct is a value type that is copied on every assignment and pass, while a class is a reference type whose object is shared. An enum gives names to related constants, and a [Flags] enum packs several options into one value using bits.

17.1 The problem: where did the money go?

C#
var wallet = new Wallet { Balance = 500 };AddMoney(wallet, 100);Console.WriteLine($"Outside: {wallet.Balance}"); void AddMoney(Wallet w, decimal amount){    w.Balance += amount;    Console.WriteLine($"Inside:  {w.Balance}");} struct Wallet{    public decimal Balance { get; set; }}
Output
$ dotnet run Wallet.csInside:  600Outside: 500
  • Wallet is a struct (value type), so passing it to AddMoney made a full copy.
  • The method changed only the copy; the copy disappeared when the method ended.
  • With a struct, every assignment and every pass creates a new copy.

17.2 Fix: class = reference type

  • Change one word: struct -> class.
  • The method now gets a reference to the same object: 600 inside and outside.
  • Also the right design: a wallet is an entity with identity that changes over time.
Output
$ dotnet run Wallet.csInside:  600Outside: 600

17.3 How it works: value type vs reference type

Struct copy vs class reference
  1. 1.Struct variable holds the whole value

  2. 2.Assign / pass a struct: the value is copied

  3. 3.Class variable holds a reference to a heap object

  4. 4.Assign / pass a class: only the reference is copied

  5. 5.Both variables change the same object

Struct: value copy, class: reference copy

Pointstructclass
KindValue typeReference type
Assign / passWhole value copiedReference copied, object shared
InheritanceCannot inherit (can implement interfaces)Single inheritance
nullNot null (unless Nullable<T>)Can be null
Best forSmall, value-like data (Money, GeoPoint)Entities with identity (Wallet, Order)

17.4 readonly struct: an immutable value

  • Use a struct when the type is small and behaves like one value: Money = amount + currency.
  • readonly struct: nothing can change after creation.
  • Add returns a new Money instead of changing the price.
C#
var price = new Money(499, "INR");var total = price.Add(new Money(100, "INR"));Console.WriteLine(price);Console.WriteLine(total); readonly struct Money(decimal amount, string code){    public decimal Amount { get; } = amount;    public string Currency { get; } = code;    public Money Add(Money other)        => new(Amount + other.Amount, Currency);    public override string ToString()        => $"{Amount} {Currency}";}
Output
$ dotnet run Money.cs499 INR599 INR
  • Adding a setter (public decimal Amount { get; set; }) to a readonly struct is a compile error, so the copy bug cannot happen:
Output
$ dotnet run Money.csMoney.cs(5,20): error CS8341: Auto-implemented  instance properties in readonly structs  must be readonly.The build failed. Fix the build errors and run again.

17.5 enum: named constants

  • An enum is a group of related named constants (order status).
  • Values start at 0 by default: Pending 0, Shipped 1, Delivered 2, Cancelled 3.
  • switch expression maps each status to a message; Enum.TryParse converts a string from a DB/API.
C#
var status = OrderStatus.Shipped;Console.WriteLine($"{status} = {(int)status}"); string message = status switch{    OrderStatus.Pending => "Packing your order",    OrderStatus.Shipped => "On the way",    _ => "Check the order page"};Console.WriteLine(message);if (Enum.TryParse("Delivered", out OrderStatus s))    Console.WriteLine((int)s); enum OrderStatus{ Pending, Shipped, Delivered, Cancelled }
Output
$ dotnet run Order.csShipped = 1On the way2

17.6 Checkpoint: an undefined enum value

C#
var status = (OrderStatus)7;Console.WriteLine(status);Console.WriteLine(Enum.IsDefined(status));
Output
$ dotnet run Order.cs7False
  • No error: an enum is just an int underneath, so 7 is accepted.
  • Validate numbers from outside with Enum.IsDefined (or TryParse).

17.7 [Flags]: combine options with bits

C#
var rights = Access.Read | Access.Write;Console.WriteLine(rights);Console.WriteLine(rights.HasFlag(Access.Write));Console.WriteLine(rights.HasFlag(Access.Delete)); rights |= Access.Delete;rights &= ~Access.Write;Console.WriteLine(rights); [Flags]enum Access{    None = 0, Read = 1, Write = 2, Delete = 4}
Output
$ dotnet run Access.csRead, WriteTrueFalseRead, Delete
Flags operations step by step
  1. 1.Read | Write -> 0011 (Read, Write)

  2. 2.HasFlag(Write) -> True, HasFlag(Delete) -> False

  3. 3.rights |= Delete -> 0111 (adds a bit)

  4. 4.rights &= ~Write -> 0101 (removes a bit)

  5. 5.Print -> Read, Delete

Powers of two = one bit per option

OperationSyntaxMeaning
Combinea | bBoth options on
Checkx.HasFlag(a)Is option a on?
Addx |= aTurn option a on
Removex &= ~aTurn option a off

17.8 Common mistakes

  • Flags values left auto-numbered (None, Read, Write, Delete): Delete = 3 = Read + Write, so Access.Delete.HasFlag(Access.Read) is True. Use explicit powers of two (1, 2, 4) and None = 0.
  • Thinking a struct always lives on the stack: value type means copy semantics; a struct that is a class field or array element lives on the heap.
  • Thinking a struct is always faster: a big struct is fully copied on every pass and can be slower.
  • Using a mutable struct for something with identity (the wallet bug).
  • Trusting numbers cast to an enum without IsDefined/TryParse.

17.9 5 rules for struct and enum

  1. Small, value-like type: struct.
  2. Make structs readonly.
  3. Identity or changing state: class.
  4. No magic numbers: enum + validate outside values.
  5. Flags: powers of two, None = 0.

17.10 Interview tips

  • struct = value type, copied on assign/pass; class = reference type, only the reference is copied and the object is shared.
  • A struct cannot inherit but can implement interfaces; use readonly struct for small immutable values.
  • Stack vs heap depends on context, not just struct vs class.
  • enum = named int constants; [Flags] enum stores multiple options in one value with bitwise operators.