C# | constructors is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class.
Example :
class Tech { ....... // Constructor public Tech() {} ....... } // an object is created of Tech class, // So above constructor is called Tech obj = new Tech();
Important points to Remember About Constructors
- Constructor of a class must have the same name as the class name in which it resides.
- A constructor can not be abstract, final, and Synchronized.
- Within a class, you can create only one static constructor.
- A constructor doesn’t have any return type, not even void.
- A static constructor cannot be a parameterized constructor.
- A class can have any number of constructors.
- Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
Types of Constructor
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Private Constructor
- Static Constructor
Default Constructor
A constructor with no parameters is called a default constructor. A default constructor has every instance of the class to be initialized to the same values. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class.
Example :
// C# Program to illustrate calling // a Default constructor using System; namespace DefaultConstructorExample { class Tech { int num; string name; // this would be invoked while the // object of that class created. Tech() { Console.WriteLine("Constructor Called"); } // Main Method public static void Main() { // this would invoke default // constructor. Tech tech1 = new Tech(); // Default constructor provides // the default values to the // int and object as 0, null // Note: // It Give Warning because // Fields are not assign Console.WriteLine(tech1.name); Console.WriteLine(tech1.num); } } }
Output :
Constructor Called 0
Note : This will also show some warnings as follows:
prog.cs(8, 6): warning CS0649: Field `DefaultConstructorExample.Tech.num' is never assigned to, and will always have its default value `0' prog.cs(9, 9): warning CS0649: Field `DefaultConstructorExample.Tech.name' is never assigned to, and will always have its default value `null'
Parameterized Constructor
A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values.
Example:
// C# Program to illustrate calling of // parameterized constructor. using System; namespace ParameterizedConstructorExample { class Tech { // data members of the class. String name; int id; // parameterized constructor would // initialized data members with // the values of passed arguments // while object of that class created. Tech(String name, int id) { this.name = name; this.id = id; } // Main Method public static void Main() { // This will invoke parameterized // constructor. Tech tech1 = new Tech("TAS", 1); Console.WriteLine("TechName = " + tech1.name + " and TechId = " + tech1.id); } } }
Output :
TechName = TAS and TechId = 1
Copy Constructor
This constructor creates an object by copying variables from another object. Its main use is to initialize a new instance to the values of an existing instance.
Example :
// C# Program to illustrate calling // a Copy constructor using System; namespace copyConstructorExample { class Tech { private string month; private int year; // declaring Copy constructor public Tech(Tech s) { month = s.month; year = s.year; } // Instance constructor public Tech(string month, int year) { this.month = month; this.year = year; } // Get details of Tech public string Details { get { return "Month: " + month.ToString() + "\nYear: " + year.ToString(); } } // Main Method public static void Main() { // Create a new Tech object. Tech g1 = new Tech("June", 2018); // here is g1 details is copied to g2. Tech g2 = new Tech(g1); Console.WriteLine(g2.Details); } } }
Output :
Month: June Year: 2018
Private Constructor
If a constructor is created with private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class.
Points To Remember :
- It is the implementation of a singleton class pattern.
- use private constructor when we have only static members.
- Using private constructor, prevents the creation of the instances of that class.
Example :
// C# Program to illustrate calling // a Private constructor using System; namespace privateConstructorExample { public class Tech { // declare private Constructor private Tech() { } // declare static variable field public static int count_Tech; // declare static method public static int Tech_Count() { return ++count_Tech; } // Main Method public static void Main() { // If you uncomment the following // statement, it will generate // an error because the constructor // is unaccessible: // Tech s = new Tech(); // Error Tech.count_Tech = 99; // Accessing without any // instance of the class Tech.tech_Count(); Console.WriteLine(Tech.count_tech); // Accessing without any // instance of the class Tech.tech_Count(); Console.WriteLine(Tech.count_tech); } } }
Output :
100 101
Static Constructor
Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and to be executed only once.
Points To Remember :
- It can’t be called directly.
- When it is executing then the user has no control.
- It does not take access modifiers or any parameters.
- It is called automatically to initialize the class before the first instance created.
Example :
// C# Program to illustrate calling // a Static constructor using System; namespace staticConstructorExample { class Tech { // It is invoked before the first // instance constructor is run. static Tech() { // The following statement produces // the first line of output, // and the line occurs only once. Console.WriteLine("Static Constructor"); } // Instance constructor. public Tech(int i) { Console.WriteLine("Instance Constructor " + i); } // Instance method. public string Tech_detail(string name, int id) { return "Name:" + name + " id:" + id; } // Main Method public static void Main() { // Here Both Static and instance // constructors are invoked for // first instance Tech obj = new Tech(1); Console.WriteLine(obj.Tech_detail("TAS", 1)); // Here only instance constructor // will be invoked Tech obj1 = new Tech(2); Console.WriteLine(obj1.Tech_detail("TechforTech", 2)); } } }
Output :
Static Constructor Instance Constructor 1 Name:TAS id:1 Instance Constructor 2 Name:TechforTech id:2
Recent Comments