Cheung Tat Ming Cheung Tat Ming - 1 month ago 17
C# Question

C# reference assignment operator?

for example:

int x = 1;
int y = x;
y = 3;
Debug.WriteLine(x.ToString());


Is it any reference operator instead of "=" on line:3,
to make the x equal to 3 , if i assign y =3 .

Answer

'int' is a value type and so copies the value on assignment, as you have discovered.

You could use pointers in the traditional C/C++ sense by using an 'unsafe' block but then the pointers are only usable inside that block which limits its use. If instead you want to access the value outside of an 'unsafe' block then you need to convert to using a reference instead.

Something like this...

var x = new Tuple<int>(1);
var y = x;
y.Item1 = 3;
Comments