Managed Reference Types

  • Thread starter Thread starter The unProfessional
  • Start date Start date
T

The unProfessional

Hi everyone,

I've been developing .net apps for some time now, but there are still some
things that're unclear in regards to how .Net manages pointers internally.

ArrayList lst = new ArrayList ();
....
lst.Add (new MyClass());
....
MyClass c = (MyClass) lst[0]; // <-- Is this a pointer or a new copy of
the object??


If I then modify a member of the class pointed to by "c", it isn't reflected
in the version that's still stored
in the ArrayList. Why is this? Does .Net make another copy of the object
when I cast it down from the ArrayList? If so, WHY? And if not, why are my
changes not reflected?

It seems to me that allocation should only occur for reference types when
you use the "new" operator... otherwise, you should simply be dealing with
pointers. All value types (native or structures) are always on the stack
(rather than the heap), right? Clarification would be much appreciated.


Thanks in advance
 
In that particular example, it should be a reference to the MyClass object
that was inserted earlier. Changes in c are reflected in the arraylist
unless there was something else happening that is not shown in code.


public class Test
{
public static void Main() {

ArrayList a = new ArrayList();
a.Add(new AnotherClass());
PrintMyId(((AnotherClass)a[0])); //<-- prints 0

AnotherClass c = (AnotherClass)a[0];
c.MyId = 23;
PrintMyId((AnotherClass)c); //<-- Prints 23
PrintMyId(((AnotherClass)a[0]));// <--- prints 23
}

public static void PrintMyId(AnotherClass a){
Console.WriteLine(a.MyId);
}

public class AnotherClass {
public int MyId { get{ return _id; } set { _id =
alue; } }
int _id;
}
}


Of course, if that was a valuetype, you would end up with a copy so you will
not see the change reflected.
Am I mssing something?
 
Back
Top