What is a constructor in C# and why would you use it?
Experience Level: Junior
Tags: C#
Answer
A constructor is a special method in a class.
It is called immediately after the new object is created based on the class (remember, the class is a blueprint based on which an object can be created).
The purpose of a constructor is to initialize values of the newly constructed object to predefined values.
The constructor must always have the same name as the class.
There can be multiple constructors in the class with the same name, but each constructor needs to have different number of parameters or the parameters must be of different type.
Related C# job interview questions
How do you recognize a method call in C#?
C# JuniorWhat is a method in C# and how do you define one?
C# JuniorWhat parts does a C# class usually contain?
C# JuniorWhat is a project in Visual Studio and what file extension does it have?
C# JuniorWhat is a solution in Visual Studio and what file extension does it have?
C# Junior