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! π
π What You Are Going to Learn
βοΈ What is a Constructor?
βοΈ Why do we need Constructors in C#?
βοΈ Types of Constructors in C#
βοΈ What is a Destructor?
βοΈ When to use a Destructor in C#?
βοΈ Real-world scenarios with code 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! π