I'm trying to understand when a object is recycled. For example, in a class I have a List declaration and a method inside this class to populate the list by declaring and initializing a temporary object and then adding this object to the list.
My confusion: Since the temporary objects were declared within the body of the method, wouldn't these objects be recycled when the method returns and thus the list which held references to them now lose their object's values? My code still keeps the object values (and presumably reference intact) after method completion.
public class CameraTest
{
private List <Camera> cameraList;
public CameraTest()
{
AddCamera();
}
private void AddCamera()
{
Camera tempCamera = new Camera();
tempCamera.Name="Camera1";
cameraList.Add(tempCamera);
}
//Why would cameraList still have the "Camera1" object here?
}
The garbage collector in .NET is non-deterministic. An object is "ready for collection" once there are no more references to it, but that doesn't mean it'll be collected right away.
In your code, cameraList
has the object with name "Camera1" in it because it references it, so it prevents it to be collected, no matter the scope.
The scope is meant for variables, not for objects. Objects are references in memory, while variables are just pointers to those references. You lose the variable tempCamera
, but not the object it points to