Suppose a survival game updates many enemies each frame. A C# struct is a value type suited to small, fixed-size data whose fields are used together, such as a Vector2 position. Choosing a struct rather than a class affects how that data is stored and copied—and therefore the cost of updating it. section 2.1
Use these practical checks when choosing between a struct and a class:
- Keep structs small: 16 bytes or less is a guideline, not a hard limit. Vector2 is 8 bytes; Vector4 is 16 bytes. section 2.1
- Group fields that are used together. A position’s x and y coordinates fit; a container holding several arrays of enemy data is better as a class. section 2.1
- Prefer fixed-size value fields. Arrays and strings refer to heap data, so placing them inside a struct does not make that data inline. section 2.1 section 2.8
Listing 2.1 C# class holding all the data for all enemies
public class EnemyData
{
public Vector2[] Position;
public Vector2[] Direction;
public float[] Velocity;
}The enemy-data container is a class because it holds arrays; the position and direction arrays contain Vector2 structs. An array of structs stores its elements contiguously, while an array of classes holds references to separately placed objects. section 2.1 section 2.8
A temporary enemy position
Create a local Vector2 from two random values, then assign it to an enemy’s position array. The local temporary is removed when the function exits, and assignment copies its value. Creating a temporary class object instead adds a heap allocation that remains until garbage collection. section 2.4
Listing 2.14 Correct example of passing a struct using ref
public void MovePlayerHorizontally(ref Vector2 position, float amount)
{
position.x += amount;
}
GameData gameData = new GameData();
MovePlayerHorizontally(ref gameData.PlayerPosition, 10.0f);Passing a Vector2 to a function normally passes a copy: changing that parameter does not move the original player position. Use ref when the function must modify the original without copying the struct; alternatively, return the changed value and assign it back. section 2.4.1
A struct is not necessarily on the stack: a struct field inside a heap-allocated class lives with that object. Also avoid boxing and needless copies, especially with larger structs. Passing an entire class can be convenient, but passing the specific data to modify makes the function’s effects clearer. Measure performance on the target device; editor behavior can differ. section 2.4.1 section 2.1















