Note that there are some explanatory texts on larger screens.

plurals
  1. POc# - reference type referencing another reference type
    primarykey
    data
    text
    <p>Note: This applies to both List and ArrayList</p> <p>Take a look at the following simple code:</p> <pre><code>class Creature { public string Name; } class Game { // This is a reference type public Creature CurrentCreature; } class Program { static void Main(string[] args) { // First, we'll create 2 objects and let the // reference type "CurrentCreature" points to one of them Creature dragon = new Creature(); dragon.Name = "Dragon"; Creature Unicorn = new Creature(); dragon.Name = "Unicorn"; Game game = new Game(); game.CurrentCreature = dragon; // Now we'll create a list which will contain // the reference type "CurrentCreature" List&lt;Creature&gt; list = new List&lt;Creature&gt;(); list.Add(game.CurrentCreature); foreach (Creature c in list) { Console.WriteLine(c.Name); // Output is "Dragon" } // Now, we'll let "CurrentCreature" point to a different object game.CurrentCreature = unicorn; // The reference in the list still pointing to the original object!!! foreach (Creature c in list) { Console.WriteLine(c.Name); // Output is "Dragon"!!! } Console.ReadLine(); } } </code></pre> <p>I checked how a list adds an item and there is no instantiation of a new object. This is List.Add method (using Reflector tool)</p> <pre><code> public void Add(T item) { if (this._size == this._items.Length) { this.EnsureCapacity(this._size + 1); } this._items[this._size++] = item; // No instantiation this._version++; } </code></pre> <p>So, why is this happenning? The element in the list should be a reference to the object pointed to by "CurrentCreature" or is it not? Isn't it similar to the following code if we remove the list?:</p> <pre><code>class A { public B X; } class B { public string Name; } .... A a = new A(); B b1 = new B(); b1.Name = "b1"; B b2 = new B(); b2.Name = "b2"; a.X = b1; Console.WriteLine(a.X.Name); // output: b1 b1 = b2; Console.WriteLine(a.X.Name); // output: b1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload