In this chapter you will learn:
- What is Constructor and Destructors in C#?
- What is the use of Constructors and Destructors?
- How to initialize Constructors and Destructors?
Constructors and Destructors are the small chapter in C# and can be learned quickly. It is very easy to understand concept of constructors and destructors.
What are Constructors and Destructors in C#?
Constructors: Constructors are the special method of class which is used when initializes object. It looks like similar to method but it has same name as class. It is created with the same name of class and notable thing is that it never returns value so you can’t use this method for returning some value.
Guidelines while creating Constructors:
- It should be the same name of class.
- It never returns value so don’t create constructors with return type.
- A class may have several constructors
- A constructors may initialize with our without argument.
General form of constructors
public Hello(int num)
public Hello(string msg)
Destructors (~): Destructors are used to removing all the instance of classes and releasing resources. It is actually works like a garbage collector. It is useful to use destructor for security reasons as it clears memory by removing all the instance of objects and classes.
Guidelines while creating Destructors:
- Destructor is used followed by tilde (~) Symbol
- It is only used with class not the structs
- A class can only have one destructor
- It is cannot be overloaded or inherited.
- It cannot be called. It is invoked automatically.
- It does not have parameters.
General form of Destructors
~Hello() // destructor
// cleanup statements...
Constructors Destructors Chapters
Lists of Content
- Constructor Destructor Overview
- Destructor (~)
- Constructor Overloading
I know it is difficult to understand constructors and destructors by reading theory but after checking constructor examples in next chapter you will be damn clear of its concept. In the next chapter you will learn How to Use Constructor in Program