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)?
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
Yep, I realize my question was based on a misunderstanding, as both variables in my question continue to refer to the same actual storage. Assigning the value of
a
tob
just tries to update the referenced storage with its own value, which does nothing.