Tutorial by Examples

Given the following class: public class FinalizableObject { public FinalizableObject() { Console.WriteLine("Instance initialized"); } ~FinalizableObject() { Console.WriteLine("Instance finalized"); } } A program that create...
Rule of thumb: when garbage collection occurs, "live objects" are those still in use, while "dead objects" are those no longer used (any variable or field referencing them, if any, has gone out of scope before the collection occurs). In the following example (for convenience, Fi...
What if two (or several) otherwise dead objects reference one another? This is shown in the example below, supposing that OtherObject is a public property of FinalizableObject: var obj1 = new FinalizableObject1(); var obj2 = new FinalizableObject2(); obj1.OtherObject = obj2; obj2.OtherObject = ...
Weak references are... references, to other objects (aka "targets"), but "weak" as they do not prevent those objects from being garbage-collected. In other words, weak references do not count when the Garbage Collector evaluates objects as "live" or "dead". T...
Implement Dispose() method (and declare the containing class as IDisposable) as a means to ensure any memory-heavy resources are freed as soon as the object is no longer used. The "catch" is that there is no strong guarantee the the Dispose() method would ever be invoked (unlike finalizers...
As Dispose() and finalizers are aimed to different purposes, a class managing external memory-heavy resources should implement both of them. The consequence is writing the class so that it handles well two possible scenarios: When only the finalizer is invoked When Dispose() is invoked first and...

Page 1 of 1