Whenever an instance of a class is allocated, the compiler automatically executes a special method called a constructor. The purpose of the constructor is to initialize the fields within a class. It is common to use a constructor to initialize new reference types, as well as to pass existing objects to be acted on by the class.
Defining a constructor is optional but typically recommended. Also, you may overload the constructor with as many methods as needed, as long as the method signature is unique. If you do create your own constructor, make sure that you also create a default constructor that takes no parameters.
A constructor signature requires that the name of the constructor be the same as the name of the class and that the method contains no return value. The variable part is the number and order of the parameters. This is where you have the power to overload the constructor.
| Note |
If you choose to write your own constructor, you must provide at least a minimum method definition for the constructor, if you wish to use a simulated default constructor. |
The following example demonstrates a constructor and initialization.
using System; namespace Client.Chapter_5___Building_Your_Own_Classes { class CTOR { public int[] MyIntArray; public int Y; //Initialization can take place here private int ObjectCount = 0; static void Main(string[] args) { CTOR X = new CTOR(); X.ObjectCount++; CTOR YY = new CTOR(10); } //Default CTOR CTOR() { MyIntArray = new int[10]; //Do work necessary during object creation } //Overloads the CTOR allowing you to initialize Y CTOR(int myY) { Y = myY; } } }