eman eman - 1 year ago 55
C# Question

Conflict in the fact that object is a ref type

I've read about ref and value types in c# but don't know in the following example why

y = 10
are reference types?

object x = 10;
object y = x;
x = 20;
Console.WriteLine(y); //why y = 10 although x and y are reference types?

And if you convince me of the reason, how could I change the object that is referenced by both x and y?

Answer Source

I got your answers and this example may make the thing clearer.

class Complex
    public int real;
    public int imag;

static void Main(string[] args)
    Complex c1 = new Complex();
    Complex c2 = new Complex();
    c2.real = 100;
    c2.imag = 100;

    object x = c1;
    object y = x;

    ((Complex)x).imag = 50; //y here is changed

    x = c2; //y here isn't changed because this line makes x is now pointing on sth else which doesn't matter with the object referenced by y

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download