Constructors In C#, Types Of Constructors Continued

In our previous post we learned about what is constructor, why it is used and what are default and parameterized constructors. So let's learn about the remaining three types of constructors, copy constructor, static constructor and private constructor.


what are constructors and types of constructors continued



Copy Constructor


This is yet another type of parameterized constructor, but with a twist. In this constructor, the parameter passed is of same class type whose constructor is in making. It is used to copy contents of one class to another without referring to the old copy, a new instance of class is created instead. Too many words to munch in?? Consider the below example as it will help you relate these words

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CheezyCodeApp
{
    class Automobile
    {
        public int numberOfWheels;
        public int seatingCapacity;

        public Automobile()
        {
            //Default Constructor            
        }


        public Automobile(Automobile oldInstance)
        {
            numberOfWheels = oldInstance.numberOfWheels;
            seatingCapacity = oldInstance.seatingCapacity;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Automobile oldInstance = new Automobile();
            oldInstance.numberOfWheels = 5;
            oldInstance.seatingCapacity = 6;

            //Passing oldInstance as a parameter to copy constructor.
            Automobile newInstance = new Automobile(oldInstance);

            //Changed values of oldInstance
            oldInstance.numberOfWheels = 2;
            oldInstance.seatingCapacity = 3;


            Console.WriteLine(oldInstance.numberOfWheels);
            Console.WriteLine(oldInstance.seatingCapacity);

            Console.WriteLine(newInstance.numberOfWheels);
            Console.WriteLine(newInstance.seatingCapacity);
            Console.ReadLine();


            //Outputs
            //2
            //3
            //5
            //6
        }
    }
}

In above example copy constructor is the one in which Automobile class is passed as parameter. Purpose of this constructor is to copy contents of one class instance into another. But you may wonder that this thing can be done by simply assigning one class instance reference to another like

newInstance = oldInstance;

This may work but the problem here is that, the content is not actually copied from oldInstance to newInstance. Here newInstance has just got the reference from oldInstance i.e both classes objects are pointing to same memory locations and any change in any of these classes will in reflected in both.

So copy constructor is the solution to this problem, it doesn't pass reference of class but it actually creates new memory location for the new class and you can copy the contents from old class to new. In the above example we have copied 5,6 from oldInstance to newInstance and later on we have deliberately changed the values of oldInstance variables to 2,3. You can notice that both the classes output different values.


Static Constructor


Static constructor is used to initialize value of a static variable inside a class. If you don't know about static keyword, we will introduce it to you later in this series. Till that time understand anything specified static in .Net, gets memory allocation at start of application and remains active till the run-time of application.

Static constructor is called only once before first instance of the class is created. It runs irrespective of the instantiation being done by parameterized or parameterless constructor. It helps setting the value of static variables at the beginning of the instance and those values are accessible in every instance.

Shown below is an example of static constructor

using System;
using System.Threading;

namespace CheezyCodeApp
{
    class Application
    {
        //static variables
        private static DateTime startedAt;
        private static int instanceCount;
        //property to set current time at instance creation
        private DateTime CurrentTime { get; set; }
        
        //Static Constructor
        static Application()
        {
            //setting static variable
            instanceCount = 0;
            startedAt = DateTime.Now;
            Console.WriteLine("Application Started at " + startedAt);
        }

        public Application()
        {
            CurrentTime = DateTime.Now;
            instanceCount++;
            Console.WriteLine("Instance " + instanceCount + " created at " + CurrentTime);
        }

        
    }
    class Program
    {
        static void Main(string[] args)
        {
            Application app = new Application();
            Thread.Sleep(1000);
            Application app1 = new Application();
            Thread.Sleep(1000);
            Application app2 = new Application();
            Console.ReadLine();


            //Outputs
            //Application Started at 08/08/2016 22:39:16
            //Instance 1 created at 08/08/2016 22:39:16
            //Instance 2 created at 08/08/2016 22:39:17
            //Instance 3 created at 08/08/2016 22:39:18

        }
    }
}

In the above example, we have set values for startedAt & instanceCount in static constructor. Also we printed Application started at in it. Now in default constructor, we have set the value of CurrentTime property, and incremented the value of instanceCount by 1.

Now notice the code in the main function. We have written code to create instances of Application class. In the output before printing the Instance 1 created, Application started message is printed because of the main reason of static constructor. Is gets called before creation of first instance of the class.


Private Constructor


This constructor is also related to word static. Those who don't know about it will be helped out shortly in upcoming posts. Private constructors are those which prevents instantiation of a class. If a class has static members to be available for use then private constructors are used to make sure no one creates an instance of the class as the fields are static and can be accessed directly.

static fields of a class can be accessed directly like className.fieldName  without using the new keyword to create instance.

Consider the below example for private constructor

using System;

namespace CheezyCodeApp
{
    public class Counter
    {
        private Counter() { }
        public static int count;
        public static int IncreaseCount()
        {
            //Increases the count by 1
            return ++count;
        }
    }

    class TestCounter
    {
        static void Main()
        {
            //Can't create instance, compiler says Counter() is inaccesible due to it's protection level
            //Counter aCounter = new Counter(); 

            //static fields can be accessed without instance
            Counter.count = 5;
            Counter.IncreaseCount();
            Console.WriteLine("Count: " + Counter.count);

            Console.ReadLine();

            //Output
            //Count: 6
        }
    }
}

In the above example, the compiler stops us to create an instance due to it's protection level. But as the fields are static we can use them directly without creating instance. Private constructors are used to implement Design Patterns in code like Singleton pattern. A common example of class having private constructor is Math class which is present in System namespace.

So that's all about constructors. You can create a console application at your end and copy paste this code to understand the logic. You can also find out more information by changing some code here and there by yourself. Do let us know if you stuck anywhere or you can come by to say hello.

Let us know if you have any query or concerns. Happy Reading (refer full series here - C# Tutorial Index)

Comments

Popular posts from this blog

Just Maths - Views, View Groups and Layouts

Create Android Apps - Getting Started