pass by value 還是 pass by ref

pass by value 還是 pass by ref ? 兩者是不同的觀念,但好像總沒確認過c#的行為,現在簡單驗正一下.

簡單歸納結論

c#中如果是struct或是基礎類型的變數通過method是pass by value,除非你多加ref關鍵字宣告 ,如果是class生成的物件通過method預設就是pass by ref.

明明是很簡單的結論,但好像書本或是文章都沒提到這事.

        class test
        {
            public int a = 0;
        }

        struct test2
        {
            public int a;

            public test2(int _a)
            {
                a = _a;
            }
        }

        void  method1( test t , int v )
        {
            t.a = v;
        }

        void method2( test2 t , int v )
        {
            t.a = v;
        }

        void method22(ref test2 t, int v)
        {
            t.a = v;
        }

        void method3(int v1 , int v2)
        {
            v1 = v2;
        }

        void method3(ref int v1, int v2)
        {
            v1 = v2;
        }

        int value = 3; 

        private void button1_Click(object sender, EventArgs e)
        {
            test a1 = new test();
            method1(a1, 13);
            Console.WriteLine(a1.a); //13 by ref

            test2 a2 = new test2(0);
            method2(a2, 10);
            Console.WriteLine(a2.a); //0 by value

            method22(ref a2, 15);
            Console.WriteLine(a2.a);//15 by ref

            method3(value, 14);
            Console.WriteLine(value);//3 by value

            method3(ref value, 14);
            Console.WriteLine(value);//14 by ref
        }