I assumed that when we pass the reference type to a function, it is pointing to the same object and any changes will be reflected in the main method. But when I initialize the reference to a new object the behavior is not as expected. I understand that it can be done using "ref" keyword but I would to know about this behavior.
class Program
{
static void Foo(StringBuilder x)
{
x = new StringBuilder(); //if this is not initialized, "helloworld" is printed i.e., same object is getting modified.
x.Append("world");
}
static void Main(string[] args)
{
StringBuilder y = new StringBuilder();
y.Append("hello");
Foo(y);
Console.WriteLine(y.ToString());//I was expecting "world" here.
Console.ReadLine();
}
}