Introduction
In this blog, I will explain the constructor in C#. A constructor is a special function of the class that is automatically invoked whenever an instance of the class or struct is created.
The constructor function initializes the class object. The constructor of a class must have the same name as the class name and access to initialize the data members. Furthermore, a constructor is mainly used to initialize the private fields of the class while creating an instance for the class.
When you have not created a constructor in the class, the compiler will automatically create a default constructor of the class. When a class object goes out of scope, a special function called the destructor gets executed. The constructor function name and the destructor have the same name as the class tag. Both the functions don’t have any return type, not even void. They are not associated with any data type.
The constructors can be divided into five types: Default Constructor, Parameterized Constructor, Copy Constructor, Static Constructor, and Private Constructor.
Syntax
- public class Test {
- public Test() {}
- }
Example
- public class Test {
- int Speed_A, Speed_B;
- public Test() {
- Speed_A = 50;
- Speed_B = 100;
- }
- public static void Main() {
- Test obj = new Test();
- Console.WriteLine(obj.Speed_A);
- Console.WriteLine(obj.Speed_B);
- Console.Read();
- }
- }