Search code examples
c#parametersparameter-passingpass-by-valuereference-type

Default parameter passing in C#


Maybe an old question, but am not finding anything comprehensive on the internet.

If the default parameter passing method in C# is By value, then how does it affect the initial Reference Type variable?

I.e. in the below example, why will it print "Hello World" instead of just "Hello", if it was parameter passing by value?

void Foo (StringBuilder x)
{
    x.Append (" World");
}   

StringBuilder y = new StringBuilder();
y.Append ("Hello");
Foo (y);
Console.WriteLine (y);

Solution

  • Anything other than the primitive types (such as int, byte etc) are passed by reference by default. You are passing the same StringBuilder instance to the method.