Warm tip: This article is reproduced from stackoverflow.com, please click
c# reference

Assigning to reference variable

发布于 2020-03-27 10:27:54

Using C# 7.3. In this code:

int a = 0;
ref int b = ref a;
...
...
b = ref a;
b = a;
  • Are the two last assignments exactly equivalent (assigning a reference), in spite one assigns the value of a while the other assigns the reference of a? If so why?

  • If not, why is it allowed to assign a value to a ref variable (last line)?

Questioner
mins
Viewed
18
2019-07-03 23:22

No, they're not the same; it is clearer if you use more values; here a is just a dummy to initialize - the important bit is how the usage with c and d work differently; with b = ref c; we update the reference that b points to to c, so if we look at c afterwards: it is different; with b = d; we update the value of the thing that b points at, so it behaves very differently - b still points at the location of variable c.

    int a = 0;
    ref int b = ref a;
    int c = 1, d = 2;


    b = ref c;
    b = 42;
    System.Console.WriteLine(c); // 42
    System.Console.WriteLine(d); // 2

    b = d;
    b = 64;
    System.Console.WriteLine(c); // 64
    System.Console.WriteLine(d); // 2

If we compare in terms of pointers, and say that b was an int* pointer:

  • b = ref a; is b = &a
  • b = a is *b = a