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
