C# Destructor & this

HTML
CSS
C#
SQL

Destructor & This in C#

Destructors

In C#, destructors are special methods called automatically when an object is about to be destroyed or garbage collected. Unlike constructors, destructors cannot be called explicitly. They are typically used for cleanup tasks, such as releasing resources like file handles, database connections, or memory allocations. The destructor is denoted by the ~ symbol followed by the class name.

using System;

class ResourceHandler

{

    // Constructor

    public ResourceHandler()

    {

        Console.WriteLine(“ResourceHandler instance created.”);

    }

    // Destructor

    ~ResourceHandler()

    {

        Console.WriteLine(“ResourceHandler instance destroyed.”);

        // Clean up resources here

    }

    // Custom ToString() method to provide a meaningful representation of the object

    public override string ToString()

    {

        return “ResourceHandler object clear garbage”;

    }

}

class Program

{

    static void Main(string[] args)

    {

        // Creating an object of ResourceHandler

        ResourceHandler handler = new ResourceHandler();

        // Printing the object using the custom ToString() method

        Console.WriteLine(handler);

    }

}

Output: ResourceHandler instance created.
ResourceHandler object clears garbage

This

In C# programming, this is a keyword that refers to the current instance of the class. There can be 2 main usages of this keyword in C#.

It can be used to refer current class instance variable. It is used if field names (instance variables) and parameter names are the same, that is why both can be distinguish easily.

It can be used to pass a current object as a parameter to another method.

using System;

public class Employee

{

    public int id;

    public String name;  

    public Employee(int id, String name)

    {

        this.id = id;

        this.name = name;

    }

    public void display()

    {

        Console.WriteLine(id + ” ” + name );

    }

}

class TestEmployee

{

    public static void Main(string[] args)

    {

        Employee e1 = new Employee(101, “Sonoo”);

        Employee e2 = new Employee(102, “Mahesh”);

        e1.display();

        e2.display();

    }

}

Output: 101 Sonoo
102 Mahesh

using System;

public class Employee

{

    public int id;

    public string name;

    public Employee(int id, string name)

    {

        this.id = id;

        this.name = name;

    }

    public void display()

    {

        Console.WriteLine(id + ” ” + name);

        // Passes the current object to another method

        AnotherClass.PrintEmployeeDetails(this);

    }

}

public class AnotherClass

{

    public static void PrintEmployeeDetails(Employee emp)

    {

        Console.WriteLine(“Employee Details:”);

        Console.WriteLine(“ID: ” + emp.id);

        Console.WriteLine(“Name: ” + emp.name);

    }

}

class TestEmployee

{

    public static void Main(string[] args)

    {

        Employee e1 = new Employee(101, “Sonoo”);

        Employee e2 = new Employee(102, “Mahesh”);

        e1.display();

        e2.display();

    }

}

Using Destructors with IDisposable

Output:  101 Sonoo
Employee Details:
ID: 101
Name: Sonoo
102 Mahesh
Employee Details:
ID: 102
Name: Mahesh

Practices Tasks

IDisposable Pattern:

Follow the IDisposable pattern when dealing with destructors for resource cleanup.

Implement the IDisposable interface, call Dispose explicitly, and suppress finalization.

public class ResourceHandler : IDisposable

{

    // Dispose method for explicit resource cleanup

    public void Dispose()

    {

        // Explicit cleanup code

        // …

        // Suppress finalization since cleanup is handled

        GC.SuppressFinalize(this);

    }

 

    // Destructor (Finalizer)

    ~ResourceHandler()

    {

        // Cleanup code for releasing resources

    }

}

Resource Management:

Use destructors for managing unmanaged resources (e.g., file handles, network connections).

Consider alternatives like using statements and managed resources for simpler resource management.

public class FileHandler : IDisposable

{

    // Managed resource

    private FileStream fileStream;

 

    // Constructor

    public FileHandler(string filePath)

    {

        fileStream = new FileStream(filePath, FileMode.Open);

    }

 

    // Dispose method for explicit resource cleanup

    public void Dispose()

    {

        // Cleanup code for managed resource

        fileStream.Close();

        // Suppress finalization since cleanup is handled

        GC.SuppressFinalize(this);

    }

 

    // Destructor (Finalizer)

    ~FileHandler()

    {

        // Cleanup code for unmanaged resource

    }

}