Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a reference type from int

Tags:

c#

.net

i tried:

int i = 5;
object o1 = i; // boxing the i into object (so it should be a reference type)
object o2 = o1; // set object reference o2 to o1 (so o1 and o2 point to same place at the heap)

o2 = 8; // put 8 to at the place at the heap where o2 points

after running this code, value in o1 is still 5, but i expected 8.

Am I missing something?

like image 977
Milo711 Avatar asked Nov 30 '12 19:11

Milo711


2 Answers

That's not how variables in C# work. It has nothing to do with boxing value types.

Consider this:

object o1 = new object();
object o2 = o1;

o2 = new object();

Why would you expect o1 and o2 to contain a reference to the same object? They are the same when you set o2 = o1, but once you set o2 = new object(), the value (the memory location pointed to by the variable) of o2 changes.

Maybe what you're trying to do can be done like this:

class Obj {
    public int Val;
}

void Main() {
    Obj o1 = new Obj();
    o1.Val = 5;
    Obj o2 = o1;
    o2.Val = 8;
}

At the end of Main, the Val property of o1 will contain 8.

like image 180
ken Avatar answered Oct 06 '22 06:10

ken


To do what you want to do, the value has to be a property of a reference type:

public class IntWrapper
{
    public int Value { get; set; }
    public IntWrapper(int value) { Value = value; }
}

IntWrapper o1 = new IntWrapper(5);
IntWrapper o2 = o1;

o2.Value = 8; 
like image 27
phoog Avatar answered Oct 06 '22 06:10

phoog