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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| 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;} |

