65
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[値型]と[参照型]、[値渡し]と[参照渡し]がそろってる言語で実行例を出す

Last updated at Posted at 2014-10-16

これで値の値渡しと値の参照渡しと参照の値渡しと参照の参照渡しの違いが分かっただろう

実行コード

using System;

class Program {
    struct ValWrap { public int value; }
    class RefWrap { public int value; }

    static void swapAndEdit(ValWrap left, ValWrap right) {
        var tmp = left;
        left = right;
        right = tmp;
        tmp.value *= 100;
    }
    static void swapAndEdit(RefWrap left, RefWrap right) {
        var tmp = left;
        left = right;
        right = tmp;
        tmp.value *= 100;
    }
    static void swapAndEdit(ref ValWrap left, ref ValWrap right) {
        var tmp = left;
        left = right;
        right = tmp;
        tmp.value *= 100;
    }
    static void swapAndEdit(ref RefWrap left, ref RefWrap right) {
        var tmp = left;
        left = right;
        right = tmp;
        tmp.value *= 100;
    }

    static void Main() {
        {
            Console.WriteLine("値の値渡し");
            var left = new ValWrap();
            left.value = 1;
            var right = new ValWrap();
            right.value = 2;
            swapAndEdit(left, right);
            Console.WriteLine(left.value + ", " + right.value);
        }
        {
            Console.WriteLine("参照の値渡し");
            var left = new RefWrap();
            left.value = 1;
            var right = new RefWrap();
            right.value = 2;
            swapAndEdit(left, right);
            Console.WriteLine(left.value + ", " + right.value);
        }
        {
            Console.WriteLine("値の参照渡し");
            var left = new ValWrap();
            left.value = 1;
            var right = new ValWrap();
            right.value = 2;
            swapAndEdit(ref left, ref right);
            Console.WriteLine(left.value + ", " + right.value);
        }
        {
            Console.WriteLine("参照の参照渡し");
            var left = new RefWrap();
            left.value = 1;
            var right = new RefWrap();
            right.value = 2;
            swapAndEdit(ref left, ref right);
            Console.WriteLine(left.value + ", " + right.value);
        }
    }
}

実行結果

値の値渡し
1, 2
参照の値渡し
100, 2
値の参照渡し
2, 1
参照の参照渡し
2, 100
65
61
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
65
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?