Complete C# Tutorial

πŸ’€ Destructor (~) in C# – Say Goodbye to Unused Objects!

πŸ‘‹ Introduction: What Happens When an Object is No Longer Needed?

Hey there, C# learner! πŸŽ‰ Ever wondered what happens when an object is no longer needed? Does it just sit there wasting memory? Nope! C# has a smart feature called the Garbage Collector (GC) that automatically frees up memory. But what if you need to clean up resources manually before the object is destroyed?

That’s where the Destructor (~) in C# comes in! πŸ—‘οΈ It helps in cleaning up memory just before an object is removed from memory. Sounds cool, right? Let’s dive in! πŸš€

🧐 What is a Destructor (~) in C#?

A Destructor (~) is a special method that automatically gets called when an object is about to be destroyed. It is used to free up resources like files, database connections, or network streams before the object is removed from memory.

Β 

πŸ’‘ Key Features of a Destructor (~) in C#:

βœ”οΈ Has the same name as the class but starts with ~
βœ”οΈ No return type, no parameters
βœ”οΈ Cannot be called manually – It is triggered automatically
βœ”οΈ Used to clean up unmanaged resources (like files and database connections)

Β 

πŸš€ How Garbage Collector in C# Works with Destructors?

The Garbage Collector (GC) in C# automatically deletes objects when they are no longer in use. But before doing that, if the class has a Destructor (~), the GC will call it first to clean up resources.

Think of it like this:

🧹 Garbage Collector in C# = A robot that cleans memory
πŸ—‘οΈ Destructor (~) in C# = A final goodbye method before deletion

Now, let’s see it in action! 🎬

πŸ› οΈ Syntax of Destructor (~) in C#

The Destructor (~) in C# follows a simple syntax:

				
					class ClassName  
{  
    // Constructor  
    public ClassName()  
    {  
        Console.WriteLine("Constructor: Object Created!");  
    }  

    // Destructor  
    ~ClassName()  
    {  
        Console.WriteLine("Destructor: Object Destroyed!");  
    }  
}
				
			

πŸ“Œ Explanation of Syntax:

  • class ClassName β†’ Defines a class in C#.
  • public ClassName() β†’ This is the constructor that runs when an object is created.
  • ~ClassName() β†’ This is the destructor that runs before an object is destroyed.
  • No parameters, no return type β†’ Unlike normal methods, destructors don’t accept parameters and don’t return anything.
  • Called automatically β†’ The Garbage Collector in C# calls the destructor when needed.

This ensures automatic memory cleanup and helps avoid memory leaks! πŸš€

πŸ—οΈ Example 1: Basic Destructor in C#

Let’s create a class with a destructor and see when it gets called.

Β 

πŸ–₯️ Code Example:

				
					using System;

class Demo
{
    public Demo()
    {
        Console.WriteLine("Constructor: Object Created!");
    }

    ~Demo()
    {
        Console.WriteLine("Destructor: Object Destroyed!");
    }
}

class Program
{
    static void Main()
    {
        Demo obj1 = new Demo();
    }
}
				
			
πŸ–₯️ Output (May vary due to Garbage Collection timing):
				
					Constructor: Object Created!  
Destructor: Object Destroyed!  
				
			

πŸ“Œ Explanation of Syntax:

  • The constructor runs when the object is created.
  • The destructor (~Demo) runs when the object is destroyed.
  • The Garbage Collector in C# calls the destructor automatically.

Easy, right? Now, let’s take it up a notch! πŸš€

πŸ“ Example 2: Destructor for Cleaning File Resources

Imagine you open a file to write data, but forget to close it. That could cause memory leaks! Let’s fix that using a Destructor (~) in C#.

Β 

πŸ–₯️ Code Example:

				
					using System;
using System.IO;

class FileHandler
{
    StreamWriter writer;

    public FileHandler()
    {
        writer = new StreamWriter("example.txt");
        writer.WriteLine("Hello, Destructor!");
        Console.WriteLine("File Opened and Written!");
    }

    ~FileHandler()
    {
        writer.Close();
        Console.WriteLine("Destructor: File Closed!");
    }
}

class Program
{
    static void Main()
    {
        FileHandler obj = new FileHandler();
    }
}
				
			
πŸ–₯️ Output
				
					File Opened and Written!  
Destructor: File Closed!  
				
			

πŸ“Œ Explanation of Syntax:

  • The constructor opens the file and writes data.
  • The destructor closes the file automatically before the object is deleted.
  • The Garbage Collector in C# calls the destructor when memory needs to be freed.

No more memory leaks! πŸŽ‰

🏦 Real-World Example: Bank Account System

Imagine a bank system that connects to a database. Before an account object is deleted, it must disconnect from the database.

Β 

πŸ–₯️ Code Example:

				
					using System;

class BankAccount
{
    public BankAccount()
    {
        Console.WriteLine("Database Connection Opened!");
    }

    ~BankAccount()
    {
        Console.WriteLine("Destructor: Database Connection Closed!");
    }
}

class Program
{
    static void Main()
    {
        BankAccount acc1 = new BankAccount();
    }
}
				
			
πŸ–₯️ Output
				
					Database Connection Opened!  
Destructor: Database Connection Closed!  
				
			

πŸ“Œ Explanation of Syntax:

  • The constructor opens the database connection.
  • The destructor closes the connection when the object is deleted.
  • The Garbage Collector in C# ensures no resources are wasted.

🎯 Why is Destructor (~) in C# Important?

🎯 Destructor (~) in C# is useful because:

βœ”οΈ It prevents memory leaks by cleaning up resources.
βœ”οΈ It ensures files, database connections, and network resources are closed properly.
βœ”οΈ It works automatically, so you don’t have to worry about it.

Without destructors, unused objects could eat up memory and slow down your application. So, always free up resources when you don’t need them! πŸš€

πŸŽ‰ Conclusion

πŸ’‘ Destructor (~) in C# is a lifesaver when it comes to freeing up memory and cleaning up resources.
πŸ’‘ It works with the Garbage Collector in C# to delete objects when they’re no longer needed.
πŸ’‘ It’s simple, automatic, and prevents memory leaks.

You’ve now mastered destructors! πŸŽ“ Time to use them in your projects! πŸš€

Β 

πŸ”œ Next What?

In the next chapter, you’ll learn about Dispose() Method in C# – how to clean memory instantly! πŸ’ͺ

Leave a Comment

Share this Doc

Destructor (~)

Or copy link