Constructors in C# Explained

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
  1. public class Test {  
  2.  public Test() {}  
  3. }  
Example
  1. public class Test {  
  2.  int Speed_A, Speed_B;  
  3.  public Test() {  
  4.   Speed_A = 50;  
  5.   Speed_B = 100;  
  6.  }  
  7.  public static void Main() {  
  8.   Test obj = new Test();  
  9.   Console.WriteLine(obj.Speed_A);  
  10.   Console.WriteLine(obj.Speed_B);  
  11.   Console.Read();  
  12.  }  
  13. }