Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array holding reference to extinct object

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());

    }
like image 423
Joel B Avatar asked Dec 28 '22 11:12

Joel B


1 Answers

When you set:

array[0] = foo;

You're actually doing a by-value copy of the reference to the object pointed to by foo, and copying that reference into "array[0]".

Later, when you do:

foo = bar;

You're doing the same thing - copying, by value, the reference to the object pointed to by bar, into the variable foo. This has no effect on array[0], since the reference was copied by value originally. In order to make the first DerivedClass1 instance (foo's original reference) a candidate for GC, you need to explicitly set array[0] to some other reference (or null).

like image 165
Reed Copsey Avatar answered Jan 13 '23 09:01

Reed Copsey