GC will run and you can do nothing about it. Its
automatic and non deterministic, meaning you cannot determine/ guess when garbage collection will run.
-
object o = "123";
-
object k = o;
-
o = null;
-
//
-
1.Assigning null reference to managed objects wont help. GC automatically releases the memory for objects that are no longer referenced. In above eg, o references string "123" and then k references o. If o is assigned null, it wont change anything wrt to memory that has string "123" (it wont just disappear). Object k still references string "123". Only when no objects reference string "123", GC will run and clear memory referenced by string "123".
2. For unmanaged objects its necessary to implement
IDisposable.
"Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object."
MSDN Link
"The garbage collector's optimizing engine determines the best time to perform a collection based on the allocations being made. When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots. Every application has a set of roots. Each root either refers to an object on the managed heap or is set to null. An application's roots include global and static object pointers, local variables and reference object parameters on a thread's stack, and CPU registers. The garbage collector has access to the list of active roots that the just-in-time (JIT) compiler and the runtime maintain. Using this list, it examines an application's roots, and in the process creates a graph that contains all the objects that are reachable from the roots."
MSDN