wjtk4444 wjtk4444 - 1 year ago 83
C# Question

Making value type behave like a reference type using boxing and implicit conversions

I would like to box a value type and give it implicit conversions. Unfortunately doing so makes it stop behaving like a reference type i.e.

MyTnt i1 = 3; //MyValue has a field value = 3
MyInt i2 = 5; //value = 5

i1 = i2; //both i1 and i2 = 5
i2 = 4; //i1 = 5, i2 = 4; should be i1 = i2 = 4;

Is it possible to write boxing using implicit conversions so it behaves here as expected?

Answer Source

I believe you're misunderstanding some points.

One thing is creating references to hold an object or a value type, and another story is giving an argument by reference.

i1 would also hold 4 if you would pass it by reference in some method:

public void X(int i2, ref MyInt i1)
   // When you define a ref parameter
   // you're not creating a new reference but you're
   // reusing the given one
   i1 = i2;

MyInt i1 = 4;
MyInt i2 = 0;     

// This would produce what you expect
X(i2, ref i1);

// Now i2 is 4
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download