Consider the following case:
public class Test
{
public Test()
{
text = "By default";
}
public string text { get; set; }
public void GiveMeClass(Test t)
{
t.text = "I have a class";
}
public void GiveMeRef(ref Test t)
{
t.text = "I have a ref";
}
}
calling code:
Test t = new Test();
Console.WriteLine(t.text);
t.GiveMeClass(t);
Console.WriteLine(t.text);
t.GiveMeRef(ref t);
Console.WriteLine(t.text);
this will writeline the following texts:
By default
I have a class
I have a ref
Now if we change code in the methods by assigning t new instance of Test class, like in the code below:
public class Test
{
public Test()
{
text = "By default";
}
public string text { get; set; }
public void GiveMeClass(Test t)
{
t = new Test() { text = "I have a class" };
}
public void GiveMeRef(ref Test t)
{
t = new Test() { text = "I have a ref" };
}
}
the calling code will writeline the following texts:
By default
By default
I have a ref
As you can see the instance of Test class did not change when GiveMeClass method was called (because the output text was "By default", not "I have a class"). So the question is, if the classes are passed by reference to methods why did not the assignment t = new Test() { text = "I have a class" };
change the original instance of Test class in the caller code?