I thought that if a C# array held reference types it would simply hold references to each of the objects, however the code below tells me otherwise. It appears as if the array is holding a reference to an object of which I thought was set to be garbage collected. I feel like i'm missing something fundamental here. Can anyone tell me why the array reference does not change when foo is reassigned?
abstract class AbstractBaseClass
{
protected int _someProperty;
public virtual int SomeProperty
{
get
{
return _someProperty;
}
set
{
_someProperty = value;
}
}
}
class DerrivedClass1 : AbstractBaseClass
{
}
class DerrivedClass2 : AbstractBaseClass
{
public override int SomeProperty
{
get
{
return _someProperty + 1;
}
set
{
_someProperty = value;
}
}
}
static void Main()
{
AbstractBaseClass foo;
AbstractBaseClass bar;
AbstractBaseClass[] array = new AbstractBaseClass [1];
foo = new DerrivedClass1();
foo.SomeProperty = 99;
array[0] = foo;
Console.WriteLine("Value of foo.SomeProperty: " + foo.SomeProperty.ToString());
bar = new DerrivedClass2();
bar.SomeProperty = 99;
Console.WriteLine("Value of bar.SomeProperty: " + bar.SomeProperty.ToString());
foo = bar;
Console.WriteLine("Value of foo.SomeProperty after assignment: " + foo.SomeProperty.ToString());
Console.WriteLine("Value of array[0] after assignment: " + array[0].SomeProperty.ToString());
}