Constructor is a special method of a class or struct.
When a class or struct is created, its constructor is called. Constructors have the same name as the class or struct, and they usually initialize the data members of the new object.
Types of Constructors
Basically constructors are 5 types those are
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Static Constructor
- Private Constructor
Class Constructors:
Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.
Here you need to remember that a class can have any number of constructors and constructors don’t have any return type, not even void and within a class we can create only one static constructor.
Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.
Default Constructor:
A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below
namespace ConsoleApplication1 { class SampleClass { public string x, y; public SampleClass() { x = "Shashangka"; y = "Shekhar"; } } class Program { static void Main(string[] args) { // Initialize:Once object of class created // Automatically constructor will be called SampleClass obj = new SampleClass(); Console.WriteLine(obj.x + " " + obj.y); Console.ReadLine(); } } }
OutPut:
Shashangka Shekhar
Parameterized Constructor:
A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below
namespace ConsoleApplication1 { class SampleClass { public string x, y; // Declaring Parameterized constructor with Parameters public SampleClass(string a, string b) { x = a; y = b; } } class Program { static void Main(string[] args) { // Initialize:Once object of class created // Automatically constructor will be called // Parameterized Constructor Called SampleClass obj = new SampleClass("Shashangka", "Shekhar"); Console.WriteLine(obj.x + " " + obj.y); Console.ReadLine(); } } }
OutPut:
Shashangka Shekhar
Copy Constructor
A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for this
namespace ConsoleApplication1 { class SampleClass { public string x, y; // Declaring Parameterized constructor with Parameters public SampleClass(string a, string b) { x = a; y = b; } public SampleClass(SampleClass objSample) { x = objSample.x; y = objSample.y; } } class Program { static void Main(string[] args) { // Initialize:Once object of class created // Automatically constructor will be called // Parameterized Constructor Called SampleClass obj = new SampleClass("Shashangka", "Shekhar"); // obj copied to obj1 SampleClass obj1 = new SampleClass(obj); Console.WriteLine("Original:" + obj.x + " " + obj.y); Console.WriteLine("Copied:" + obj1.x + " " + obj1.y); Console.ReadLine(); } } }
OutPut:
Original: Shashangka Shekhar
Copied: Shashangka Shekhar
Static Constructor
A static constructor is a member that implements the actions required to initialize a class. Static constructors are declared using static-constructor-declarations.
Static constructors are not inherited, and cannot be called directly.
The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
- An instance of the class is created.
- Any of the static members of the class are referenced.
- Static constructor will not accept any parameters because it is automatically called by CLR.
- Static constructor will not have any access modifiers.
- Static constructor will execute automatically whenever we create first instance of class
- Only one static constructor will allowed.
namespace ConsoleApplication1 { class SampleClass { public static int X; static SampleClass() { X = 1; Console.WriteLine("Result:" + X); } } class Program { static void Main(string[] args) { // Initialize:Once object of class created // Automatically constructor will be called SampleClass obj = new SampleClass(); Console.ReadLine(); } } }
OutPut:
Result: 1
Private Constructor:
A private constructor is a special instance 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. For example:
namespace ConsoleApplication1 { class SampleClass { private SampleClass() { } public static int currentCount; public static int IncrementCount() { return ++currentCount; } } class Program { static void Main(string[] args) { // Initialize:Once object of class created // Automatically constructor will be called SampleClass.currentCount = 100; SampleClass.IncrementCount(); Console.WriteLine("New count: {0}", SampleClass.currentCount); Console.ReadLine(); } } }
OutPut:
New count: 101
Error if Instantiated: ‘SampleClass.SampleClass()’ is inaccessible due to its protection level
Struct Constructors:
Struct constructors are similar to class constructors, except for the following differences:
- Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
- A struct cannot have an initializer in the form: base (argument-list).
Example
The following is an example of a constructor using two arguments for the Point struct.
namespace ConsoleApplication2 { public struct MyPoint { private int x, y; // Constructor: public MyPoint(int x, int y) { this.x = x; this.y = y; } // Override the ToString method: public override string ToString() { return (String.Format("({0},{1})", x, y)); } } class Program { static void Main(string[] args) { // Initialize two points: MyPoint p1 = new MyPoint(); MyPoint p2 = new MyPoint(10, 15); // Display the results using the overriden ToString method: Console.WriteLine("Point:1[default initialization]: {0}", p1); Console.WriteLine("Point:2[explicit initialization]: {0}", p2); Console.ReadLine(); } } }
OutPut:
Point:1[default initialization]: (0,0)
Point:2[explicit initialization]: (10,15)
Syed Maftahur Rahman Sohel says:
Excillent
Shashangka Shekhar says:
Thanks
says:
I’m regularly following your blog. The more I read i’m getting it informative for beginner and novice like me.