What is finalizer in C#?
๐ก Concept: Finalizer
A finalizer (destructor) is a special method in C# that is called by the garbage collector before reclaiming an object's memory to perform cleanup.
๐ Quick Intro
Finalizers are used to release unmanaged resources when the Dispose method has not been called explicitly.
๐ง Analogy
Think of a finalizer as the last cleaning crew that tidies up a room after everyone has left but before the room is locked.
๐ง Technical Explanation
- ๐ Finalizers are declared using destructor syntax (~ClassName).
- ๐งน Called non-deterministically by the garbage collector.
- โ ๏ธ Can introduce performance overhead if misused.
- ๐ Used as a safety net if Dispose isn't called.
- ๐ก Prefer IDisposable and Dispose method for timely cleanup.
๐ฏ Use Cases
- โ Cleaning up unmanaged resources as a backup.
- โ Releasing handles if Dispose is missed.
- โ Ensuring resource release in legacy code.
- โ Final chance to free resources before object destruction.
๐ป Code Example
public class Sample {
~Sample() {
// Cleanup code here
Console.WriteLine(""Finalizer called"");
}
}

โ Interview Q&A
Q1: What is a finalizer?
A: A method called by the GC before object memory is reclaimed.
Q2: How is a finalizer declared?
A: Using destructor syntax: ~ClassName()
Q3: Is finalizer deterministic?
A: No, it is called non-deterministically.
Q4: When should you use finalizers?
A: As a safety net if Dispose is not called.
Q5: Can finalizers cause performance issues?
A: Yes, if misused.
Q6: How to avoid finalizers?
A: Implement IDisposable and call Dispose.
Q7: Can you force finalizer execution?
A: No, GC controls finalization timing.
Q8: What happens if finalizer throws exception?
A: It is ignored, and finalization continues.
Q9: Does C# have destructors?
A: Yes, finalizers act as destructors.
Q10: What is GC.SuppressFinalize?
A: Prevents finalizer from running if Dispose is called.
๐ MCQs
Q1. What is a finalizer in C#?
- Method called manually
- Method called by GC before reclaiming memory
- Constructor
- Destructor
Q2. How is a finalizer declared?
- Dispose()
- ~ClassName()
- Finalize()
- Destructor()
Q3. Is finalizer deterministic?
- Yes
- No
- Sometimes
- Always
Q4. When to use finalizers?
- Always
- Never
- As a safety net
- For managed resources
Q5. Can finalizers cause performance issues?
- No
- Yes
- Sometimes
- No idea
Q6. How to avoid finalizers?
- Ignore
- Implement IDisposable
- Use GC
- Call Dispose
Q7. Can you force finalizer?
- Yes
- No
- Maybe
- Sometimes
Q8. What if finalizer throws exception?
- Crashes app
- Ignored by runtime
- Throws error
- Stops GC
Q9. Does C# have destructors?
- No
- Yes
- Sometimes
- No idea
Q10. What is GC.SuppressFinalize?
- Runs finalizer
- Prevents finalizer if disposed
- Calls Dispose
- None
๐ก Bonus Insight
Finalizers should be used sparingly and in conjunction with IDisposable to ensure efficient resource cleanup.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!