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
