Complete C# Tutorial

C# Constructor & Destructor – Explained with Examples

Hey there, C# learner! πŸ‘‹

Ever wondered how objects in C# come to life and how they disappear when no longer needed? That’s where Constructors and Destructors step in!

Think of a constructor as a welcoming host at a party. The moment you arrive (create an object), they set up everything for you. On the other hand, a destructor is like the cleaning staffβ€”they ensure everything is cleaned up after you leave (object is destroyed).

Sounds interesting? Let’s dive in and understand this with real-world examples! πŸš€

By the end of this tutorial, you’ll understand how constructors initialize objects and how destructors help clean up resources in C# applications. πŸš€

🎯 Constructor in C#

A constructor is a special method in a class that gets called automatically when an object is created. It helps initialize values and set up things for the object.

πŸ›  How to Initialize a Constructor in C#?

In C#, a constructor is a special method that has:

βœ” The same name as the class
βœ” No return type (not even void)
βœ” Runs automatically when an object is created

Example 1: Basic Constructor Initialization

				
					using System;

class Car
{
    public string Brand;

    // Constructor
    public Car()
    {
        Brand = "Unknown";
        Console.WriteLine("A new car is created!");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car(); // Constructor runs automatically
    }
}
				
			

πŸ–₯ Expected Output:

				
					A new car is created!
				
			

πŸ“ Explanation:

βœ” We created an object using new Car();
βœ” The constructor ran automatically and initialized Brand with "Unknown"
βœ” The message "A new car is created!" was displayed

But wait, what if we want to set values dynamically when creating an object? πŸ€” Let’s explore parameterized constructors!

πŸš€ Initializing Constructors with Parameters

Instead of using default values, we can pass values when creating objects.

Β 

Example 2: Constructor with Parameters

				
					using System;

class Car
{
    public string Brand;

    // Parameterized Constructor
    public Car(string carBrand)
    {
        Brand = carBrand;
        Console.WriteLine($"A new {Brand} car is created!");
    }
}

class Program
{
    static void Main()
    {
        Car myCar1 = new Car("Tesla"); 
        Car myCar2 = new Car("BMW");  
    }
}
				
			

πŸ–₯ Expected Output:

				
					A new Tesla car is created!
A new BMW car is created!
				
			

πŸ“ Explanation:

βœ” We passed "Tesla" and "BMW" as arguments while creating objects.
βœ” The constructor accepted the values and assigned them to the Brand property.
βœ” Now, each car object has a unique brand name! πŸš—

🌟 Different Ways to Initialize a Constructor

There are multiple ways to initialize a constructor based on your needs.

Β 

1️⃣ Default Constructor (No Parameters)

				
					class Person
{
    public string Name;

    // Default Constructor
    public Person()
    {
        Name = "Unknown";
    }
}
				
			

βœ” Automatically assigns a default value when an object is created.

2️⃣ Parameterized Constructor (Passing Values)

				
					class Person
{
    public string Name;

    // Parameterized Constructor
    public Person(string name)
    {
        Name = name;
    }
}
				
			

βœ” Allows you to set values dynamically when creating an object.

3️⃣ Constructor Overloading (Multiple Constructors)

				
					class Person
{
    public string Name;
    public int Age;

    // Default Constructor
    public Person()
    {
        Name = "Unknown";
        Age = 0;
    }

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

βœ” Multiple constructors with different parameters allow flexibility.

4️⃣ Constructor with this Keyword (Calling Another Constructor)

				
					class Person
{
    public string Name;
    public int Age;

    // Constructor Chaining
    public Person(string name) : this(name, 18) // Calls another constructor
    {
    }

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

βœ” The this keyword calls another constructor from the same class.

What Did We Learn?

βœ” A constructor initializes objects automatically when they are created.
βœ” We can initialize constructors with or without parameters.
βœ” Constructor overloading allows us to have multiple constructors for flexibility.
βœ” The this keyword can be used to call another constructor inside a class.

Now that you know how to initialize constructors, try them out in your projects and see the magic! πŸš€

πŸ›‘ Destructor in C#

A destructor is used to clean up resources before an object is removed from memory. It is:

βœ” Called automatically when an object is destroyed.
βœ” Used for cleanup, like closing files or releasing database connections.
βœ” Has the same name as the class, but starts with ~ (tilde).

Simple Destructor Example

				
					class Example
{
    // Constructor
    public Example()
    {
        Console.WriteLine("Object created!");
    }

    // Destructor
    ~Example()
    {
        Console.WriteLine("Object destroyed!");
    }
}

class Program
{
    static void Main()
    {
        Example obj = new Example();  // Constructor runs here
    }
}  // Destructor will run when the program ends
				
			

πŸ–₯ Expected Output:

				
					Object created!
Object destroyed!
				
			

πŸ“ Explanation:

  • The constructor runs when the object obj is created.
  • The destructor runs when the object is no longer needed (end of the program).

πŸš— Real-World Example: Car Showroom System

Imagine a car showroom where each time a car arrives, the system registers it with default settings. When a car leaves (sold or scrapped), it is removed from the system.

Here’s how constructors & destructors can be used in this scenario:

				
					using System;

class Car
{
    public string Brand;

    // Constructor
    public Car(string carBrand)
    {
        Brand = carBrand;
        Console.WriteLine($"πŸš— {Brand} added to the showroom.");
    }

    // Destructor
    ~Car()
    {
        Console.WriteLine($"❌ {Brand} removed from the showroom.");
    }
}

class Program
{
    static void Main()
    {
        Car myCar1 = new Car("BMW");
        Car myCar2 = new Car("Audi");

        // Objects are destroyed automatically when program ends
    }
}
				
			

πŸ–₯ Expected Output:

				
					πŸš— BMW added to the showroom.
πŸš— Audi added to the showroom.
❌ Audi removed from the showroom.
❌ BMW removed from the showroom.
				
			

πŸ“ Explanation:

βœ” The constructor initializes each new car that arrives.
βœ” The destructor removes cars when they are no longer needed.
βœ” In C#, destructors are called automatically when the object is garbage collected.

Conclusion – Key Takeaways

βœ” Constructors help in object initialization automatically.
βœ” Destructors help in cleaning up resources before an object is destroyed.
βœ” Constructors can have parameters, but destructors cannot.
βœ” Destructors are automatically called when an object is garbage collected.
βœ” If your program uses unmanaged resources (files, database connections, etc.), use destructors!

Now you know how constructors and destructors work! Keep practicing and try using them in your projects.

Β 

Next What?

In the next lesson, we will explore sizeof in C# – a powerful statement that helps you determine the memory size of different data types. You don’t want to miss this one!

πŸ‘‰ Stay tuned and keep coding! πŸš€

Β 

πŸ‘‰ If you have any difficulty or questions, drop a comment. We’ll be happy to help you! 😊

Leave a Comment

Share this Doc

Constructor & Destructor

Or copy link