Managed Reference Types

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
 
G

Girish Bharadwaj

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top