how come passing reference type by ref does not always modify the argument?
I was taught that when calling a method with a reference type as an argument, any changes made to the parameter in the method effectively modify the reference type that was used as an argument when calling the method.
In the case of data types, I was taught that the only way to implement a similar functionality is by using the ref keyword in the method before the parameter and in the method call before the argument.
That's straightforward.
But I am confused about instances when calling a method with a reference type argument, and modifying the parameter in the method, does not modify the argument.
Study the following sample code:
Code:
namespace PassingByRef
{
class Box
{
private string _s;
public string S
{
set { _s = value; }
get { return _s; }
}
public Box(string s)
{
this._s = s;
}
}
class Program
{
static void Main(string[] args)
{
Box box = new Box("Hello");
Console.WriteLine(box.S);//output: Hello
Test1(box);
Console.WriteLine(box.S);//output: Hello
Test2(box);
Console.WriteLine(box.S);//output: Hello???
Test3(ref box);
Console.WriteLine(box.S);//output: Hello!!!
Console.ReadKey();
}
static void Test1(Box x)
{
x = new Box("Hello!!!");
}
static void Test2(Box x)
{
x.S = "Hello???";
}
static void Test3(ref Box x)
{
x = new Box("Hello!!!");
}
}
}
In the case of the Test1 method, I'd like to understand why the moment the parameter was initialized "the reference was lost," whereas the reference was preserved in Test2 when only the field of the parameter was modified.
Also related to the observation concerning Test1, how come the only way to achieve the desired functionality (Test3 method) is by using the ref keyword before a reference type parameter/argument? I had imagined it was redundant.