DEV Community

Cover image for Constructors, Destructors and this in C#
AllCoderThings
AllCoderThings

Posted on

Constructors, Destructors and this in C#

Originally published at https://allcoderthings.com/en/article/csharp-constructor-destructor-and-this

In C#, classes and structs have special methods that define how objects are created and destroyed. A constructor runs when an object is created and assigns initial values. A destructor is called just before an object is removed from memory. The this keyword refers to the current instance of the class and is especially useful with parameters of the same name or for method chaining.


Constructor

A constructor is a special method with the same name as the class. It is executed automatically when a new object is created and is commonly used to assign initial values. It can take parameters and can be overloaded. If no constructor is defined, C# provides a default (parameterless) constructor.


public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    // Parameterless constructor
    public Product()
    {
        Name = "Unknown";
        Price = 0;
    }

    // Parameterized constructor
    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }

    public void Print()
    {
        Console.WriteLine($"{Name} - {Price:0.00} USD");
    }
}

class Program
{
    static void Main()
    {
        var p1 = new Product(); // parameterless
        var p2 = new Product("Notebook", 45m); // with parameters

        p1.Print(); // Unknown - 0.00 USD
        p2.Print(); // Notebook - 45.00 USD
    }
}
Enter fullscreen mode Exit fullscreen mode

Destructor

A destructor is defined by prefixing the class name with ~ and it cannot take parameters. It is called right before an object is cleaned up from memory by the Garbage Collector. While it can be used for cleanup operations like closing files or releasing memory, the .NET Garbage Collector usually makes manual destructors unnecessary.

public class Logger
{
    public Logger()
    {
        Console.WriteLine("Logger started.");
    }

    ~Logger()
    {
        Console.WriteLine("Logger cleaned up from memory.");
    }
}

class Program
{
    static void Main()
    {
        var log = new Logger();
        log = null;

        // Trigger Garbage Collector
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
Enter fullscreen mode Exit fullscreen mode

The this Keyword

this refers to the current instance of a class. It is used to distinguish between parameters and properties with the same name, for method chaining, or to call another constructor within the same class.

public class Customer
{
    public string Name { get; set; }
    public string Email { get; set; }

    // Constructor with parameter names same as property names
    public Customer(string name, string email)
    {
        this.Name = name;   // assignment using this
        this.Email = email;
    }

    // Method chaining
    public Customer SetName(string name)
    {
        this.Name = name;
        return this;
    }

    public Customer SetEmail(string email)
    {
        this.Email = email;
        return this;
    }

    public void Print()
    {
        Console.WriteLine($"{Name} - {Email}");
    }
}

class Program
{
    static void Main()
    {
        var c = new Customer("John", "john@example.com")
                    .SetName("Michael")
                    .SetEmail("michael@example.com");

        c.Print(); // Michael - michael@example.com
    }
}
Enter fullscreen mode Exit fullscreen mode

Calling a Constructor with this

You can call one constructor from another within the same class using this(...). This approach reduces repetitive code and centralizes shared initialization logic.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name) : this(name, 0) // calls another constructor
    {
    }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void Print()
    {
        Console.WriteLine($"{Name} ({Age})");
    }
}

class Program
{
    static void Main()
    {
        var p1 = new Person("Alice");
        var p2 = new Person("Mary", 25);

        p1.Print(); // Alice (0)
        p2.Print(); // Mary (25)
    }
}
Enter fullscreen mode Exit fullscreen mode

TL;DR

  • Constructor: Runs when an object is created and assigns initial values.
  • Destructor: Runs before an object is removed from memory; rarely needed since GC handles cleanup.
  • this: Refers to the current object; used for distinguishing parameters, method chaining, and calling constructors.

Top comments (1)

Collapse
 
vpospichal profile image
Vlastimil Pospíchal

Unfortunately, C# calls the destructor too late. For example, PHP calls it immediately after the descriptor expires, which is how it should be.