Constructor in C#

A Constructor is a special method of a Class, which is used to initialize the members of the same class. Whenever an Object of a class is created , a Constructor is called by default.Constructor do not return values and always have the same name as the Class.

A Derived Class can not inherit the Constructor of its Base Class. All the Derived Classes have their own default Constructor.

When you intiantiate a Derived Class , first the Constructor of Base Class is called and then derived class Constructor is called.
The Constructor of Base Class is initializes the members of the Base Class before derived class constructor is executed.
Points to Remember :-

  • The purpose of a Class Constructor is to initialize Class fields. A class Constructor is automatically called when an instance of a class is created.
  • Constructor do not return values and always have the same name as the Class.
  • Constructors are not mandatory. If we do not provide a constructor , a default parameterless constructor is automatically provided by C#.
  • Constructors can be overloaded by the Name and type of Parameters.
  • If a constructor is used to create a copy of an existing object as new Object ,then the constructor is called a copy constructor.
  • Copy constructor takes the reference of the Object to be copied as an argument.
  • C# does not provide the copy constructor by default.

What is Destructor in C# ? Describe it in details.

A Destructor or finalizer is called when the Object is finally destroyed and the garbage is collected.
Points to Remember :-

  • Destructor have the same name as the Class with ~ symbol infornt of them.
  • Destructor does not take any parameters and do not return a value.
  • Destructors are places where you could put code to release any resources your class was holding during its lifetime.
  • Destructors are normally called when the C# garbage collector decides to clean your Object from memory.
  • C# has a garbage collection mechanism that runs to destroy an Object when its reference counts drops to 0.
  • We can also destroy the objects that are no longer used ,by calling the destructor in the program.

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.