Class constructor C# Example – Learn how to create a constructor in C# programs with example and when constructors get called and its important points.

Important Points about class constructor in C# programming.

  • Class constructor is a special method that have same name as class name. For example, if a class name is “Car” then the constructor name will also be “Car”.
  • Class constructor does not have return type, means, it does not return anything. Where as methods of a class have return types.
  • Constructor get called automatically every time when we create an object the class.

In below C# source code example, when we create an object Maruti , For example, “Car maruti = new Car();” then constructor will be called automatically. You may read how to create class and object in C# with example .

Similarly, when we create object Honda, then again constructor will be called. Means, As many times as you create an object of the class using new keyword, the constructor will get called every time automatically / implicitly.

Example of  how to create a constructor in C#

  /*
 * Example of constructor in C#
 */

    class Car
    {

        public Car(){
            Console.WriteLine("Constructor..."); 
	}

        public void run(){
            Console.WriteLine("Car is running...");
	}
    }
    class Program
    {
        static void Main(string[] args)
        {
            //We we crate an object, the consturctor of the 
            //class will be called automatically.
            Car maruti = new Car();
            maruti.run();

            Car honda = new Car();//It will also call constructor of the class
            honda.run();
        }
    }

Output
Constructor…
Car is running…
Constructor…
Car is running…

Related Posts