Letβs go over constructors and destructors in C# β essential concepts for object initialization and cleanup.
π 1. Constructors
A constructor is a special method that is called automatically when an object is created.
Key Points
-
Name of constructor = class name
-
No return type, not even
void
-
Can be overloaded (multiple constructors with different parameters)
-
Used to initialize fields or properties
Example: Basic Constructor
public class Person
{
public string Name;
public int Age;
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void Greet()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
// Create object
Person person = new Person("Alice", 25);
person.Greet(); // Hello, my name is Alice and I am 25 years old.
Example: Constructor Overloading
public class Person
{
public string Name;
public int Age;
public Person() // Default constructor
{
Name = "Unknown";
Age = 0;
}
public Person(string name) // Constructor with 1 parameter
{
Name = name;
Age = 0;
}
public Person(string name, int age) // Constructor with 2 parameters
{
Name = name;
Age = age;
}
}
- Allows creating objects in different ways
π 2. Destructors
A destructor is a special method that is called automatically when an object is destroyed or garbage collected.
Key Points
-
Name =
~ClassName
-
No parameters, no return type
-
Cannot be called explicitly
-
Rarely needed in C# (garbage collector handles most cleanup)
-
Typically used to release unmanaged resources
Example: Destructor
public class Person
{
public string Name;
public Person(string name)
{
Name = name;
Console.WriteLine($"{Name} created");
}
// Destructor
~Person()
{
Console.WriteLine($"{Name} destroyed");
}
}
// Usage
Person person = new Person("Alice");
-
Destructor runs automatically when the object is garbage collected.
-
In modern C#, prefer IDisposable and using statement for resource cleanup.
π 3. Constructor vs Destructor
Feature | Constructor | Destructor |
---|---|---|
Purpose | Initialize object | Cleanup before object is destroyed |
Name | Same as class name | ~ClassName |
Return type | None | None |
Parameters | Can have parameters | Cannot have parameters |
Call | Automatically on object creation | Automatically on garbage collection |
Overloading | Yes | No |
β Tips
-
Always use constructors to set default or required values for fields.
-
Avoid relying on destructors for resource cleanup β use IDisposable instead.
-
C# automatically provides a default constructor if you donβt define one.