CSharp - Passing for reference-type

Introduction

Passing a reference-type argument by value copies the reference, but not the object.

In the following example, sb and fooSB are two variables that reference the same StringBuilder object.

Test(sb) is copying the value of sb to fooSB. It is like duplicating a room key.

fooSB is a copy of a reference, setting fooSB to null doesn't make sb null.

Demo

using System;
using System.Text;

class Prig/*  www .j a v a  2 s . co  m*/
{
    static void Test(StringBuilder fooSB)
    {
        fooSB.Append("test");
        fooSB = null;
    }

    static void Main()
    {
        StringBuilder sb = new StringBuilder();
        Test(sb);
        Console.WriteLine(sb.ToString());    // test
    }
}

Result