liveBook · Manning

Ref keyword

As explained in High Performance Unity Game Development

The C# ref keyword specifies that an argument is passed by reference so the called code can access the caller's variable directly.

Struct arguments are passed by value by default, so a function that changes its parameter may change only a copy. Use ref when the function needs to modify the caller’s struct in place. section 2.3.1 section 2.4.1

Add experience to the original game data

Declare the parameter as ref and pass the argument as ref: AddXP(ref GameDataStruct gameDataStruct, int xp) { gameDataStruct.XP += xp; } Calling AddXP(ref myGameDataStruct, 10) changes myGameDataStruct.XP directly. section 2.3.1

Listing 2.9 Adding xp to our original struct through a reference
GameDataStruct myGameDataStruct;
myGameDataStruct.XP = 0;
 
public void AddXP(ref GameDataStruct gameDataStruct, int xp)
{
    gameDataStruct.XP += xp;
}

AddXP(ref myGameDataStruct, 10);

The listing shows both required ref markers in an XP-update example. section 2.3.1

For a small value that must change in place, ref can avoid copying and makes modification visible in the function signature. It is not a blanket optimization: structs can be harder to reason about, easier to modify accidentally, and may contain heap references. Consider returning a new value instead when in-place modification is not needed. section 2.3.1 section 2.4.1

How High Performance Unity Game Development covers it

How deep it goes
Demonstrates value-copy behavior, ref-based modification, and trade-offs without delving into implementation internals.
Examples
Uses an XP update on GameDataStruct and a player-position update with Vector2.
What it assumes
Assumes familiarity with structs and function calls, while demonstrating how pass-by-value affects struct arguments.
What you can do after
Apply C# ref parameters and call-site markers to modify a struct in place.
How it connects
Connects ref parameters to structs, value types, pass-by-value behavior, and function return values.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.