Monday, 18 April 2016

Constructors and Its types in C#

Constructor is a special method of a class that will be automatically invoked when an object of a class is created. Compiler will automatically create a default constructor in the class, if no constructor is created in the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null. The main use of constructors is to initialize private fields of the class while creating an instance for the class.

A constructor doesn't have any return type, not even void. A class can have any number of constructors. A static constructor cannot be a parametrized constructor. Within a class you can create only one static constructor.

Following are types of Constructors:

1) Default Constructor:

Parameter less constructor is called a default constructor, means this type of constructor does not take parameters. The drawback of a default constructor is that every object of the class will be initialized to the same values and it is not possible to initialize each object of the class to different values. The default constructor initializes 1) All numeric fields in the class to zero 2) All string and object fields to null.

Example:

using System;

    namespace DefaultConstractorDemo
    {
        class DefaultConstractorDemoClass
        {
            public int firstNumber, secondNumber;
            public DefaultConstractorDemoClass()   //default contructor
            {
                firstNumber = 200;
                secondNumber = 450;
            }
            public static void Main()
            {
                DefaultConstractorDemoClass obj = new DefaultConstractorDemoClass(); //When an object is created , constructor is called
                Console.WriteLine(obj.firstNumber);
                Console.WriteLine(obj.secondNumber);
                Console.Read();
            }
        }
    }
When you run the application, the output will be as following:
200
450

2) Parameterized Constructor:

A constructor with at least one or more than one parameter is called a parametrized constructor. The main advantage of a parametrized constructor is that you can initialize each object of the class to different values.

Example:


using System;
    namespace DefaultConstractorDemo
    {
        class ParameterizedConstractorDemoClass
        {
            public int firstNumber, secondNumber;
            public ParameterizedConstractorDemoClass(int a, int b)  // Decalaring Paremetrized Constructor with int a,b parameter
            {
                firstNumber = a;
                secondNumber = b;
            }
        }
        class MainClass
        {
            static void Main()
            {
                ParameterizedConstractorDemoClass obj = new ParameterizedConstractorDemoClass(500, 800);   // Creating object of Parameterized Constructor and give values to it

                Console.WriteLine("Value of a = " + obj.firstNumber);
                Console.WriteLine("Value of b = " + obj.secondNumber);

                Console.Read();
            }
        }
    }
When you run the application, the output will be as in the following:
Value of a = 500
Value of b = 800

3) Copy Constructor:

The constructor which creates an object by copying attributes (variables) from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new object to the values of an existing object.

Example:

using System;
    namespace CopyConstractorDemo
    {
        class Student
        {
            private string fullName;
            private int age;
            public Student(Student student)   // Declaring a Copy constructor.
            {
                fullName = student.fullName;
                age = student.age;
            }
            public Student(string name, int age)  // Instance constructor.
            {
                this.fullName = name;
                this.age = age;
            }
            public string DetailsOfStudent     // Get deatils of Student
            {
                get
                {
                    return " The age of " + fullName + " is " + age.ToString();
                }
            }
        }

        class StudentDetail
        {
            static void Main()
            {
                Student objStudent1 = new Student("Ghazi", 25);  // Create a new Student object.
                Student objStudent2 = new Student(objStudent1);  // Here is objStudent1 details is copied to objStudent2.
                Console.WriteLine(objStudent2.DetailsOfStudent);
                Console.ReadLine();
            }
        }
    }

Now run the program, the output will be as follows:

The age of Ghazi is 25

4) Static Constructor:

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. A static constructor does not take access modifiers or have parameters. The user has no control on 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. When a constructor is created as static, it will be invoked only once for all of instances of the class and it is invoked during the creation of the first instance of the class or the first reference to a static member in the class. A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

Example:

using System;
    namespace StaticConstractorDemo
    {

        public class Teacher
        {
            static Teacher()// Static Constructor Declaration
            {
            }
            public static void Salary()
            {
                Console.WriteLine("This is from static void Salary() Method");
            }
        }
        class TeacherDetails
        {
            static void Main()
            {
                Teacher.Salary();
                Console.ReadLine();
            }
        }
    }
Now run the program, the output will be as follows:
This is from static void Salary() Method

5) Private Constructor:

It is not possible for other classes to derive from a class, if the constructor of this class is declare as private. Neither is it possible to create an object of this class. They are usually used in classes that contain static members only. It provides an implementation of a singleton class pattern. One use of a private constructor is when we have only static members.

Example:

using System;
    namespace ConstrcutorsDemo
    {
        public class MyCounter
        {
            private MyCounter()   //Decleration of Private
            {
            }
            public static int CurrentOnlineUsers;
            public static int TotalUsersVisited()
            {
                return ++CurrentOnlineUsers;
            }
        }
        class ViewOfVisitedUsers
        {
            static void Main()
            {
                //MyCounter aCounter = new MyCounter();   // Error : 'ConstrcutorsDemo.MyCounter.MyCounter()' is inaccessible due to its protection level

                MyCounter.CurrentOnlineUsers = 1300;
                MyCounter.TotalUsersVisited();
                Console.WriteLine("Now the count is: {0}", MyCounter.CurrentOnlineUsers);
                Console.ReadLine();
            }
        }
    }

Now run the program, the output will be as follows:

Now the count is : 1301



(Practice Makes a Man Perfect)

No comments: