Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments.
Types of Constructor
Copy Constructor
A constructor used for making objects by copying variables from other objects.
classPerson{ // Copy constructor.publicPerson(Person previousPerson) { Name =previousPerson.Name; Age =previousPerson.Age; } //// Alternate copy constructor calls the instance constructor. //public Person(Person previousPerson) // : this(previousPerson.Name, previousPerson.Age) //{ //} // Instance constructor.publicPerson(string name,int age) { Name = name; Age = age; }publicint Age { get; set; }publicstring Name { get; set; }publicstringDetails() {return Name +" is "+Age.ToString(); }}classTestPerson{staticvoidMain() { // Create a Person object by using the instance constructor.Person person1 =newPerson("George",40); // Create another Person object, copying person1.Person person2 =newPerson(person1); // Change each person's age.person1.Age=39;person2.Age=41; // Change person2's name.person2.Name="Charles"; // Show details to verify that the name and age fields are distinct.Console.WriteLine(person1.Details());Console.WriteLine(person2.Details()); // Keep the console window open in debug mode.Console.WriteLine("Press any key to exit.");Console.ReadKey(); }}// Output:// George is 39// Charles is 41
Instance/Parameterized Constructor
A constructor which have one or more parameters.
You declare an instance constructor to specify the code that is executed when you create a new instance of a type with the new expression.
classCoords{publicCoords() :this(0,0) { } // Instance ConstructorpublicCoords(int x,int y) // Paramaterized Constructor { X = x; Y = y; }publicint X { get; set; }publicint Y { get; set; }publicoverridestringToString() =>$"({X},{Y})";}classExample{staticvoidMain() {var p1 =newCoords();Console.WriteLine($"Coords #1 at {p1}"); // Output: Coords #1 at (0,0)var p2 =newCoords(5,3);Console.WriteLine($"Coords #2 at {p2}"); // Output: Coords #2 at (5,3) }}
Parameterless (Default) Constructor
If a class has no explicit instance constructors, C# provides a parameterless (default) constructor that you can use to instantiate an instance of that class.
publicclassPerson{publicint age;publicstring name ="unknown";}classExample{staticvoidMain() {var person =newPerson();Console.WriteLine($"Name: {person.name}, Age: {person.age}"); // Output: Name: unknown, Age: 0 }}
Private Constructor
It is generally used in classes that contain static members only.
If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
The declaration of the empty constructor prevents the automatic generation of a parameterless constructor.
publicclassCounter{privateCounter() { } // Private Constructorpublicstaticint currentCount;publicstaticintIncrementCount() {return++currentCount; }}classTestCounter{staticvoidMain() { // If you uncomment the following statement, it will generate // an error because the constructor is inaccessible: // Counter aCounter = new Counter(); // ErrorCounter.currentCount=100;Counter.IncrementCount();Console.WriteLine("New count: {0}",Counter.currentCount); // Keep the console window open in debug mode.Console.WriteLine("Press any key to exit.");Console.ReadKey(); }}// Output: New count: 101
Static Constructor
A static constructor is used to initialize any static data/fields, or to perform a particular action that needs to be performed only once.
It is called automatically before the first instance is created or any static members are referenced.
A class or struct can only have one static constructor.
publicclassBus{ // Static variable used by all Bus instances. // Represents the time the first bus of the day starts its route.protectedstaticreadonlyDateTime globalStartTime; // Property for the number of each bus.protectedint RouteNumber { get; set; } // Static constructor to initialize the static variable. // It is invoked before the first instance constructor is run.staticBus() { globalStartTime =DateTime.Now; // The following statement produces the first line of output, // and the line occurs only once.Console.WriteLine("Static constructor sets global start time to {0}",globalStartTime.ToLongTimeString()); } // Instance constructor.publicBus(int routeNum) { RouteNumber = routeNum;Console.WriteLine("Bus #{0} is created.", RouteNumber); } // Instance method.publicvoidDrive() {TimeSpan elapsedTime =DateTime.Now- globalStartTime; // For demonstration purposes we treat milliseconds as minutes to simulate // actual bus times. Do not do this in your actual bus schedule program!Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",this.RouteNumber,elapsedTime.Milliseconds,globalStartTime.ToShortTimeString()); }}classTestBus{staticvoidMain() { // The creation of this instance activates the static constructor.Bus bus1 =newBus(71); // Create a second bus.Bus bus2 =newBus(72); // Send bus1 on its way.bus1.Drive(); // Wait for bus2 to warm up.System.Threading.Thread.Sleep(25); // Send bus2 on its way.bus2.Drive(); // Keep the console window open in debug mode.Console.WriteLine("Press any key to exit.");Console.ReadKey(); }}/* Sample output: Static constructor sets global start time to 3:57:08 PM. Bus #71 is created. Bus #72 is created. 71 is starting its route 6.00 minutes after global start time 3:57 PM. 72 is starting its route 31.00 minutes after global start time 3:57 PM.*/