Thumb

What is Constructor?

1/8/2020 6:53:15 AM

Every class contain a Constructor. Constructor responsible to initialize the default value of the property or variable. Constructor name and class name must and should same. However, Constructor look like method but it has no return type. So, Constructor can’t return any things. Now we can see the example of the Constructor:

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

namespace ObjectTest
{
    internal class Students
    {
        public int a = 0;
        public Students()
        {
            this.a = 10;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Students obj = new Students();

            Console.WriteLine("The value is : " + obj.a);
            Console.ReadKey();
        }
    }
}

When student class will call then Students Constructor will call first. In the student’s class we can see the Constructor name as Students same name like class but no return type. We also see Constructor assign the value 10 and this value will print the main method.