C# ยท Chapter 39 of 46

C# Structs

A struct is a value type used to group related data together, similar to a class but with different memory behavior. Structs are copied by value when assigned or passed to methods, unlike classes which are reference types.

Structs are best suited for small, simple data groupings like a Point (x, y) or a Color (r, g, b), where the overhead of a full class isn't needed.

Syntax
struct Name {
  public type field;
}

Defining a struct

A struct is declared with the `struct` keyword and can contain fields, properties, and methods, much like a class, but is typically simpler and immutable.

Value type behavior

Because structs are value types, assigning one struct variable to another copies its data. Changing the copy does not affect the original, unlike with classes (reference types).

Example 1 (csharp)
using System;

struct Point {
  public int X, Y;
}

class Program {
  static void Main() {
    Point p1 = new Point { X = 1, Y = 2 };
    Console.WriteLine(p1.X + ", " + p1.Y);
  }
}
Output
1, 2

Point is a struct storing two int fields, X and Y.

Example 2 (csharp)
using System;

struct Point {
  public int X;
}

class Program {
  static void Main() {
    Point p1 = new Point { X = 5 };
    Point p2 = p1;
    p2.X = 10;
    Console.WriteLine(p1.X + " " + p2.X);
  }
}
Output
5 10

Since Point is a value type, p2 is a copy of p1, so changing p2 doesn't affect p1.

Key points

  • Structs are value types; classes are reference types.
  • Assigning a struct copies all of its data.
  • Structs are best for small, simple data groupings.
  • Structs can have fields, properties, and methods like classes.
๐Ÿ’ก Note: Prefer classes for complex objects with identity and behavior, and structs for small, immutable data values.

๐Ÿ“ Quick Quiz

1. Are structs value types or reference types?

2. What happens when you assign one struct variable to another?

3. What is a good use case for a struct?