I have a timer in C# which executes some code inside it’s method. Inside the code I’m using several temporary objects.
-
If I have something like
Foo o = new Foo();inside the method, does that mean that each time the timer ticks, I’m creating a new object and a new reference to that object? -
If I have
string foo = nulland then I just put something temporal in foo, is it the same as above? -
Does the garbage collector ever delete the object and the reference or objects are continually created and stay in memory?
-
If I just declare
Foo o;and not point it to any instance, isn’t that disposed when the method ends? -
If I want to ensure that everything is deleted, what is the best way of doing it:
- with the using statement inside the method
- by calling dispose method at the end
- by putting
Foo o;outside the timer’s method and just make the assignmento = new Foo()inside, so then the pointer to the object is deleted after the method ends, the garbage collector will delete the object.
Yes.
If you are asking if the behavior is the same then yes.
The memory used by those objects is most certainly collected after the references are deemed to be unused.
No, since no object was created then there is no object to collect (dispose is not the right word).
If the object’s class implements
IDisposablethen you certainly want to greedily callDisposeas soon as possible. Theusingkeyword makes this easier because it callsDisposeautomatically in an exception-safe way.Other than that there really is nothing else you need to do except to stop using the object. If the reference is a local variable then when it goes out of scope it will be eligible for collection.1 If it is a class level variable then you may need to assign
nullto it to make it eligible before the containing class is eligible.1This is technically incorrect (or at least a little misleading). An object can be eligible for collection long before it goes out of scope. The CLR is optimized to collect memory when it detects that a reference is no longer used. In extreme cases the CLR can collect an object even while one of its methods is still executing!
Update:
Here is an example that demonstrates that the GC will collect objects even though they may still be in-scope. You have to compile a Release build and run this outside of the debugger.
On my machine the finalizer is run while
SomeMethodis still executing!