C # - find a way out
I have the following C # code below.
Object first = 5;
Object second = 10;
second = first;
Console.WriteLine(first + " " + second);
Object a = 3;
Object b = a;
a = 6;
Console.WriteLine(a + " " + b);
I am getting the following output:
5 5
6 3
In fact, I expect "6 6" to be the second. Can anyone explain where I am going wrong?
Regards, Justin Samuel.
source to share
Each variable Object
will contain int
which is the type of the value. a
and there b
will be two different instances, so changing the value a
(which essentially means the reference a
refers to a new instance of int) will not change the value b
. You can modify your first code example to get a similar result:
Object first = 5;
Object second = 10;
second = first;
first = 8;
Console.WriteLine(first + " " + second); // prints "8 5"
source to share
static unsafe void Main()
{
Object first = 5;
Object second = 10;
second = first;
Console.WriteLine(first + " " + second);
int i = 3;
int y = 6;
int* a = &i;
int** b = &a;
a = &y;
Console.WriteLine(*a + " " + **b);}
execute / unsafe
5 5 6 6
:-). I would not recommend writing code this way though =)
source to share