So I'm preparing a lesson on pass-by-reference and testing my example... Here I have the following example code:
public static void Main(string[] args)
{
int x = 4;
Add(x, 4);
Console.WriteLine("x = {0}", x);
Player player = new Player("Bob");
Console.WriteLine("Your name is {0}", player.Name);
ChangeName(player, "Cobb");
Console.WriteLine("Your name is {0}", player.Name);
}
public static void Add(int x, int y)
{
x = x + y;
Console.WriteLine("(in method) x = {0}", x);
}
public static void ChangeName(Player player, string name)
{
player.Name = name;
Console.WriteLine("(in method) Your name is {0}", player.Name);
}
The first method, Add(x, 5);
works as expected, however the ChangeName method alters the player object back in the Main method scope and outputs like this:
(in method) x = 8
x = 4
Your name is Bob
(in method) Your name is Cobb
Your name is Cobb
I'm curious why this is, for years I've been teaching that the Name property of the player instance should not be changed when it comes back to the Main method scope. Have I just been teaching that incorrectly forever? Is the ref
keyword only needed for directly passing primitive data types? If that is the case, then what if I explicitly need a shallow copy of the object in the method scope?
Additional Context, in the Player class, the Name property is defined thus:
public class Player
{
/// <summary>
/// This player's name.
/// </summary>
public string Name
{
get;
set;
}
...
}