0

I don't get why d.x is 16. I assume it may have something to do with upcasting/downcasting but I'm not sure.

class C { public int x; } static void Main(string[] args) { C o = new C(); o.x = 10; C d = o; d.x = 16; Console.WriteLine(o.x); } Any help would be greatly appreciate!

9th Jan 2020, 7:37 PM
Giura Emanuel
Giura Emanuel - avatar
3 Answers
+ 3
In the line „C d = o” you created a variable „d” and assigned it a memory adress of an object you created earlier. Now both „o” and „d” point to the same memory adress, that is to the same exact object. There was only one object of type „C” created, but there are two variables that know where it is located in the memory.
9th Jan 2020, 7:46 PM
Winged
Winged - avatar
+ 4
It's just because your are assigning the reference of o to d which mean both are pointing the same location, so you can change the value of x using either o or d and it will be reflected to the other as well. o -> x then d = o o -> x <- d if you even write d.x = 20 since even o is pointing to it, also o.x will return 20.
9th Jan 2020, 7:48 PM
Avinesh
Avinesh - avatar
0
Right! I forgot that I work with classes! They are reference types and I work with references here. Thank you very much guys!
9th Jan 2020, 11:53 PM
Giura Emanuel
Giura Emanuel - avatar