AnyCompiler

Structs and Value Types

Every class on this site, in every language covered so far, is a reference type — passing an object to a method passes a reference to the same underlying object. C# adds something genuinely different: a struct is a value type. Passing a struct to a method passes a full copy, and changes inside that method never affect the original.

using System;

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

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

ModifyStruct(p1) set X to 100 — but only on its own private copy of p1. The original p1 in Main is completely untouched, which is why it still prints 1,2. If Point had been declared class instead of struct, this would print 100,2 instead — the single keyword changes the entire semantics.

Next: generics — writing one class that works across many types, with the compiler still checking type safety.

Practice exercise

Define a struct Point with fields X and Y and a constructor. Create a Point(3, 4) and print X and Y separated by a comma.