What is a Destructor in C#?

πŸ’‘ Concept: Destructor

A destructor is a special method in C# that is automatically invoked when an object is being garbage collected. It is used to clean up unmanaged resources before the object is destroyed.

πŸ“˜ Quick Intro

In C#, destructors are defined using a tilde (~) followed by the class name. They do not take parameters, cannot be overloaded, and are called by the garbage collector just before object destruction.

🧠 Analogy

Imagine you’ve stayed at a hotel. Before leaving, you tidy the room, switch off the lights, and return the key. A destructor works the same wayβ€”cleaning up before an object β€œchecks out” of memory.

πŸ”§ Technical Explanation

  • Destructors are parameterless and have no return type.
  • They are called automatically by the garbage collector.
  • They are mainly used to release unmanaged resources.
  • You cannot control the exact time of destructor execution.
  • They are not commonly needed in C# due to IDisposable and using statements.

🎯 Use Cases

  • To release unmanaged resources like file handles, sockets, or database connections.
  • To log finalization or object cleanup for debugging.
  • Rarely used in modern C# when IDisposable is preferred.

πŸ’» Code Example

public class FileManager
{
    private FileStream fileStream;

    public FileManager(string path)
    {
        fileStream = new FileStream(path, FileMode.OpenOrCreate);
    }

    ~FileManager()
    {
        // Destructor
        fileStream?.Dispose();
        Console.WriteLine("Destructor called, resources released.");
    }
}

❓ Interview Q&A

Q1: What is a destructor in C#?
A: A method called by the garbage collector before the object is destroyed.

Q2: When is a destructor executed?
A: During garbage collection, not immediately after object goes out of scope.

Q3: Can destructors be overloaded in C#?
A: No, they must not have parameters and cannot be overloaded.

Q4: Can we call a destructor explicitly?
A: No, only the GC calls it automatically.

Q5: What is the syntax for declaring a destructor?
A: ~ClassName().

Q6: Do destructors guarantee timely resource cleanup?
A: No, timing depends on GC.

Q7: Is IDisposable better than destructors?
A: Yes, it gives more control over cleanup timing.

Q8: Do structs have destructors?
A: No, only classes support destructors.

Q9: What’s the risk of relying on destructors?
A: Uncertain timing and potential memory/resource leaks.

Q10: What is the relationship between finalizers and destructors?
A: Destructors are compiled into finalizers in IL code.

πŸ“ MCQs

Q1. What is the purpose of a destructor in C#?

  • Initialize objects
  • Invoke constructors
  • Clean up unmanaged resources
  • Handle exceptions

Q2. How is a destructor defined?

  • Destructor()
  • ~ClassName()
  • void Destructor()
  • finalizer()

Q3. When is a destructor called?

  • On object creation
  • On method call
  • When object is garbage collected
  • During compilation

Q4. Can destructors be overloaded?

  • Yes
  • No
  • Only in sealed classes
  • Only with parameters

Q5. Do destructors take parameters?

  • Yes
  • No
  • Only ref parameters
  • Only out parameters

Q6. Can destructors be static?

  • Yes
  • No
  • Only in abstract classes
  • Only with IDisposable

Q7. What happens if you forget to dispose resources and don’t use a destructor?

  • Nothing
  • Memory leak may occur
  • Program crashes
  • Compiler error

Q8. Can destructors be explicitly invoked?

  • Yes
  • No
  • Only once
  • With special syntax

Q9. What is the IL equivalent of destructor?

  • Constructor
  • Interface
  • Finalizer
  • Static block

Q10. Which interface provides deterministic disposal of resources?

  • IClonable
  • IDisposable
  • IEnumerable
  • IFinalizable

πŸ’‘ Bonus Insight

Use destructors only when necessary. Prefer the IDisposable interface for better control and reliability. The garbage collector is non-deterministic, and relying on destructors alone can lead to subtle bugs or performance issues.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: