#922 – Ways in Which References to an Object Are Released
September 3, 2013 2 Comments
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; }