liveBook · Manning

Pass by reference

As explained in High Performance Unity Game Development

A parameter-passing behavior in which a function receives access to the original argument or its storage location rather than an independent copy.

In C#, structs are passed by value by default, so a function receives a copy. Add `ref` to pass the struct’s storage location instead; changes to the parameter then change the caller’s original data. section 2.3.1

Adding player experience

An `AddXP` function that accepts `ref GameDataStruct` and is called with `ref myGameDataStruct` changes the original struct’s XP value. Without `ref`, it changes only a copy. section 2.3.1

Passing by reference can avoid copying large structs, but it also makes in-place changes easier to overlook. Use it when a small value needs modification; do not use it to justify oversized structs. Reference types such as arrays and strings are passed by value too, but the copied value is a reference to the heap object. section 2.3.1 section 2.7

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);

See the C# `ref` parameter and matching call used to update the original game-data struct. section 2.3.1

How High Performance Unity Game Development covers it

How deep it goes
Explains the copy-versus-original behavior with an XP example and cautions against oversized structs and accidental mutation.
Examples
Demonstrates AddXP updating a game-data struct’s XP field.
What it assumes
Assumes familiarity with C# structs and function parameters; distinguishes struct data from references to heap objects.
What you can do after
Understand when C# ref avoids a struct copy and lets a function change the caller’s data.
How it connects
Connects structs and value types with reference types, heap storage, and copying.

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.