#922 – Ways in Which References to an Object Are Released

An object will potentially be deleted after there are no longer any references to the object.  You reference an object using a reference-typed variable.

There are several different ways in which a reference to an object can be released.

  • Change the reference-typed variable so that it refers to a different object
  • Change the reference-typed variable so that it refers to null
  • Let the reference-typed variable go out of scope (return control from the method in which the variable was declared)
        static void SomeMethod()
        {
            // myDog references the Kirby Dog object
            Dog myDog = new Dog("Kirby");

            // Refer to new Dog object,
            // no longer refer to Kirby Dog object
            myDog = new Dog("Jack");

            // Set reference to null,
            // no longer refer to Jack Dog object
            myDog = null;

            myDog = new Dog("Ruby");

            // When we leave the method, myDog
            // will go out of scope and no longer
            // refer to Ruby Dog object
            return;
        }
Advertisements

#921 – Objects Are Explicitly Created but Automatically Destroyed

You create an object, or an instance of a classusing the new keyword.  When you create the object, you must also refer to it using a reference-typed variable.

            // Create an instance of a Dog and reference it using
            // the "myDog" variable.
            Dog myDog = new Dog("Kirby", 15);

Using the new keyword, you explicitly create objects.

A;though you create objects explicitly, you never explicitly delete them.  Instead, an object can be deleted after it is no longer being referenced by any reference-typed variables.  Once the object has been deleted, the CLR (Common Language Runtime) will reclaim the memory that was being used by the object.

Not only do you not explicitly delete objects, you also can’t predict when the object will be deleted.  The CLR will decide when to delete the object, based on when it needs the memory that the object is using.