Skip to content

Instantly share code, notes, and snippets.

@yuchiki
Created July 30, 2018 11:49
Show Gist options
  • Save yuchiki/76f5a52c3b2664ddecf4729f0c4c4dd0 to your computer and use it in GitHub Desktop.
Save yuchiki/76f5a52c3b2664ddecf4729f0c4c4dd0 to your computer and use it in GitHub Desktop.
value vs reference
using System;
using System.Collections;
using System.Collections.Generic;
using static System.Console;
class Test {
public static void Main() {
var foo = new Foo("最初のテキスト"); // 値型の値
var bar = new Bar("最初のテキスト"); // 参照型の値
ref
var refFoo = ref foo; //値型の参照
ref
var refBar = ref bar; //参照型の参照
値型の値渡し(foo);
WriteLine(foo.Name);
値型の値渡し(refFoo);  // 参照から取り出された値が渡される
値型の参照渡し(ref foo);
WriteLine(foo.Name);
値型の参照渡し(ref refFoo); // 参照が渡される
参照型の値渡し(bar);
WriteLine(bar.Name);
参照型の参照渡し(ref bar);
WriteLine(bar.Name);
//...
}
static void 値型の値渡し(Foo foo) => foo.Name = "値渡し";
static void 値型の参照渡し(ref Foo foo) => foo.Name = "参照渡し";
static void 参照型の値渡し(Bar bar) => bar.Name = "値渡し";
static void 参照型の参照渡し(ref Bar bar) => bar.Name = "参照渡し";
static Foo 値型の値を返す(Foo foo) => foo;
static ref Foo 値型の参照を返す(ref Foo foo) => ref foo;
static Bar 参照型の値を返す(Bar bar) => bar;
static ref Bar 参照型の参照を返す(ref Bar bar) => ref bar;
}
struct Foo {
public string Name;
public Foo(string name) => Name = name;
}
class Bar {
public string Name;
public Bar(string name) => Name = name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment