Sunday, December 20, 2015

Constructor

How the constructor works? In C#, all steps inside a constructor are executed at first as you make an object of class.

We will see an example:
using System;

namespace Tester {
    public class Program {
        public static void Main(string[] args) {
            Console.WriteLine("Hello, world!");
            Calc calc = new Calc();
        }
    }

    public class Calc {
        int x;
        int y;
        int z;

        public Calc() {
           x = 5;
           y = 7;
           z = x * y;
           Console.WriteLine(z);
        }
    }
}

the result

We didn't use any method of Calc class in the main method to show the result of the calculation, but the result of this program shows "35" after Hello World.

This is because the Calc class has a constructor which calculates and show the result.

This constructor showed the result, so we didn't need to write any method for the calculation and showing the result. Everytime we make an object of the class, the constructor of the class is executed.

Without the constructor, this program would be as follows:
using System;

namespace Tester {
    public class Program {
        public static void Main(string[] args) {
            Console.WriteLine("Hello, world!");
            Calc calc = new Calc();
            calc.CalcA();
        }
    }

    public class Calc {
        int x;
        int y;
        int z;

        public void CalcA() {
           x = 5;
           y = 7;
           z = x * y;
           Console.WriteLine(z);
        }
    }
}

We can see, in the main method, calc.CalcA (CalcA method of Calc class) is being used.

We can compare how the constructor simplifies the program.

By the way, the constructor always have a same name as the class which contains the constructor. Plus, constructor is used as "void" (returns no value). On the other hand, the method doesn't have a same name as the class which contains the method. The method usually has a different name from the class.