Constructors and Destructors in C#
# CHAPTER 14
Constructors and Destructors
1. Introduction
When you buy a new phone, it doesn't arrive blank. It comes out of the box pre-configured with a default OS, a set battery level, and factory settings. In C#, we use Constructors to set up our objects the exact moment they are created, ensuring they are instantly ready for use.2. Learning Objectives
By the end of this chapter, you will be able to:- Define a Constructor.
- Create Parameterized Constructors.
- Overload Constructors.
-
Understand the
thiskeyword.
- Understand Destructors and Garbage Collection.
3. What is a Constructor?
A constructor is a special method inside a class that is automatically called when an object is instantiated using thenew keyword.
- It MUST have the exact same name as the class.
-
It has no return type (not even
void).
4. Parameterized Constructors
You can pass data into a constructor to customize the object the moment it is built.
5. The this Keyword
If your parameter names are exactly the same as your class field names, the compiler gets confused. You use the this keyword to specify: "I mean the variable belonging to *THIS* specific object."
6. Constructor Overloading
Just like regular methods, you can have multiple constructors in a class, as long as they have different parameters.7. Destructors (Finalizers)
A destructor is a special method called automatically right before the Garbage Collector destroys the object and frees its memory. It is denoted by a tilde (~).
Note: In modern C#, you rarely need to write destructors because the Garbage Collector handles memory perfectly. You only use them if you are dealing with unmanaged resources (like direct file handles or network streams).
8. OOP and Memory Explanation
Whennew Product("Apple") is called, the CLR allocates memory on the Heap. *Before* it returns the memory address to the Stack variable, it executes the constructor code. This ensures that it is literally impossible to use an object before its initial setup is fully complete.
9. Common Mistakes
-
Putting a return type on a constructor: If you write
public void Player(), the compiler thinks it is a normal method, NOT a constructor. It will not be called automatically.
-
Relying on Destructors for timing: You cannot predict exactly *when* the Garbage Collector will run. Therefore, you don't know exactly when the destructor will execute. For immediate cleanup, C# uses the
IDisposableinterface instead.
10. Best Practices
-
Use constructors to force the caller to provide required data. If a
Bankaccount absolutely requires an ID, make the constructor require an ID, making it impossible to create an invalid blank account.
11. Exercises
-
1.
Create a
Bookclass with a constructor that requires atitleandpages. Use thethiskeyword.
-
2.
Add a second overloaded constructor that only takes
titleand defaults the pages to100.
12. MCQs with Answers
What is the primary purpose of a Constructor?
What is the rule for naming a Constructor?
What return type does a constructor have?
What is a Default Constructor?
What does the this keyword refer to?
When is a Destructor called?
What symbol is used to denote a Destructor?
Q9. Is it necessary to manually write a destructor to free normal memory in C#? a) Yes b) No, the Garbage Collector handles it automatically Answer: b) No, the Garbage Collector handles it automatically
If you do not write ANY constructor for your class, what does the compiler do?
13. Interview Questions
-
Q: Explain the purpose of the
thiskeyword.
- Q: What is the difference between a Constructor and a Destructor?
-
Q: Why might you make a constructor
private? (Answer: To prevent external classes from creating objects, commonly used in the Singleton design pattern).
14. Summary
Constructors ensure your objects are born in a valid, ready-to-use state. You can overload them to provide multiple ways to create an object, and use thethis keyword to resolve naming conflicts. Destructors exist for cleanup, but in modern C#, the Garbage Collector usually handles that for you.