Constructor and Destructor in C#
It is used to initialize the variables in the class and used to create object for the class in memory.
Features Of Constructor:
- Constructor name & class name will be same.
- Constructor will be declared as public so that it can be called or executed in main function.
- Constructor will not have return type & will not return value.
- Constructor can contain arguments. It is called parameterized constructor.
- A class can contain more than one constructor. It is called as constructor overloading. A class can contain more than one constructor but there should be difference in a number of arguments or order of arguments or difference in datatypes.
- Default constructor means if the class is not containing constructor then compiler will use default constructor while creating object for the class. Default constructor will never take arguments.
- Private constructor can be accessed within the class. It can be executed with public constructor.
- Static constructor is used to initialize the static variables in a class.
1) Constructor containing two arguments:
'This' represents current class. It is a predefined object in c# used to work with variables in current class.
2) Constructor containing one string argument:
3) Constructor containing private & public constructor:
4) Constructor containing two public constructor:
5) Using static constructor:
Destructor is used to delete object from memory.
Features Of Destructor:
- Destructor name & class name will be same.
- Destructor will start with (~) tilde symbol.
- Destructor will not have return type & will not return value.
- Destructor will not take arguments.
- A class can contain only one destructor.
Example of destructor:
Constructor is executed when program execution is started. Destructor will execute before the program execution will end. Constructor will be called in main() & destructor will be called by the compiler. To get the same result window again press ctrl+f5. To delete unreferenced objects from heap memory, System.GC.Collect() should be used.
In this way, we have learned Constructor and destructor with examples in this article. I hope this will help beginners to understand Constructor and destructor.
You may also be interested in...
- Slack Integration with C#
- Xamarin Forms: Getting Started
- Part 1: Introduction to C#
- Part 2: Arrays and Function in C#
- Part 3: OOPs Concepts in C#
- Part 4: Constructor/Destructor in C#
- Part 5: Abstract class in C#
- Part 6: Indexer,Delegates, Anonymous Method, Lambda expression in C#
- Part 7: Collections in C#
- Part 8: Generics in C#
- Part 9: Attributes in C#
- Part 10: Sealed/Partial class in C#
- Part 11: MultiThreading in C#