What is a constructor in C#?
A special method of the class that is automatically invoked when an instance of the class is created is called a constructor. The main use of constructors is 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. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null.
Some of the key points regarding constructor are
- A class can have any number of constructors.
- A constructor doesn't have any return type, not even void.
- A static constructor can not be a parametrized constructor.
- Within a class, you can create one static constructor only.
In C#, constructors can be divided into 5 types
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Static Constructor
- Private Constructor
Now, let's see each constructor type with the example below.
Default Constructor in C#
- All numeric fields in the class to zero.
- All string and object fields to null.
Example
- using System;
- namespace DefaultConstractor
- {
- class addition
- {
- int a, b;
- public addition() //default contructor
- {
- a = 100;
- b = 175;
- }
- public static void Main()
- {
- addition obj = new addition(); //an object is created , constructor is called
- Console.WriteLine(obj.a);
- Console.WriteLine(obj.b);
- Console.Read();
- }
- }
- }
Parameterized Constructor in C#
A constructor with at least one parameter is called a parameterized constructor. The advantage of a parameterized constructor is that you can initialize each instance of the class with a different value.
- using System;
- namespace Constructor
- {
- class paraconstrctor
- {
- public int a, b;
- public paraconstrctor(int x, int y) // decalaring Paremetrized Constructor with ing x,y parameter
- {
- a = x;
- b = y;
- }
- }
- class MainClass
- {
- static void Main()
- {
- paraconstrctor v = new paraconstrctor(100, 175); // Creating object of Parameterized Constructor and ing values
- Console.WriteLine("-----------parameterized constructor example by vithal wadje---------------");
- Console.WriteLine("\t");
- Console.WriteLine("value of a=" + v.a );
- Console.WriteLine("value of b=" + v.b);
- Console.Read();
- }
- }
- }
Copy Constructor in C#
- public employee(employee emp)
- {
- name=emp.name;
- age=emp.age;
- }
- employee emp1=new employee (emp2);
Let's see its practical implementation.
- using System;
- namespace copyConstractor
- {
- class employee
- {
- private string name;
- private int age;
- public employee(employee emp) // declaring Copy constructor.
- {
- name = emp.name;
- age = emp.age;
- }
- public employee(string name, int age) // Instance constructor.
- {
- this.name = name;
- this.age = age;
- }
- public string Details // Get deatils of employee
- {
- get
- {
- return " The age of " + name +" is "+ age.ToString();
- }
- }
- }
- class empdetail
- {
- static void Main()
- {
- employee emp1 = new employee("Vithal", 23); // Create a new employee object.
- employee emp2 = new employee(emp1); // here is emp1 details is copied to emp2.
- Console.WriteLine(emp2.Details);
- Console.ReadLine();
- }
- }
- }
Static Constructor in C#
- A static constructor does not take access modifiers or have parameters.
- A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
- A static constructor cannot be called directly.
- The user has no control over when the static constructor is executed in the program.
- A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Syntax
- class employee
- {// Static constructor
- static employee(){}
- }
- using System;
- namespace staticConstractor
- {
- public class employee
- {
- static employee() // Static constructor
- declaration{Console.WriteLine("The static constructor ");
- }
- public static void Salary()
- {
- Console.WriteLine();
- Console.WriteLine("The Salary method");
- }
- }
- class details
- {
- static void Main()
- {
- Console.WriteLine("----------Static constrctor example by vithal wadje------------------");
- Console.WriteLine();
- employee.Salary();
- Console.ReadLine();
- }
- }
- }
Private Constructor in C#
- One use of a private constructor is when we have only static members.
- It provides an implementation of a singleton class pattern
- Once we provide a constructor that is either private or public or any, the compiler will not add the parameter-less public constructor to the class.
- using System;
- namespace defaultConstractor
- {
- public class Counter
- {
- private Counter() //private constrctor declaration
- {
- }
- public static int currentview;
- public static int visitedCount()
- {
- return ++ currentview;
- }
- }
- class viewCountedetails
- {
- static void Main()
- {
- // Counter aCounter = new Counter(); // Error
- Console.WriteLine("-------Private constructor example by vithal wadje----------");
- Console.WriteLine();
- Counter.currentview = 500;
- Counter.visitedCount();
- Console.WriteLine("Now the view count is: {0}", Counter.currentview);
- Console.ReadLine();
- }
- }
- }
Now run the application. The output is as follows.
If you uncomment the preceding statement that is commented in the above program then it will generate an error because the constructor is inaccessible (private).
No comments:
Post a Comment