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.
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).
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);
}
}1, 2Point is a struct storing two int fields, X and Y.
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);
}
}5 10Since 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.
