Structs
Learn how structs differ from classes in C# and when to use a value type over a reference type.
What is a Struct?
A struct looks very similar to a class — it can have fields, properties, and methods — but it is a value type, not a reference type. `int`, `double`, `bool`, and `DateTime` are all actually structs under the hood.
struct Point{ public int X; public int Y;
public Point(int x, int y) { X = x; Y = y; }}
Point p1 = new Point(1, 2);Point p2 = p1; // this COPIES the structp2.X = 99;
Console.WriteLine(p1.X); // 1 — unaffectedConsole.WriteLine(p2.X); // 99Output
Click Run to see what this code prints.
Structs vs Classes
struct
- Value type — copied on assignment
- Stored on the stack (usually)
- No inheritance (except interfaces)
- Best for small, simple data
class
- Reference type — shared on assignment
- Stored on the heap
- Supports full inheritance
- Best for complex objects with identity
When to Use a Struct
Reach for a struct when modeling a small, immutable-feeling value where copying is cheap and expected — like a 2D point, an RGB color, or money amount. Use a class for anything larger or where shared identity matters.
FAQs
No — structs cannot inherit from another struct or class (though they can implement interfaces), and nothing can inherit from a struct.
Summary
- Structs are value types, copied on assignment rather than shared by reference.
- Most built-in "primitive" types in C# are actually structs.
- Use structs for small, simple values; classes for everything else.