Default constructor in C#

CsharpProgrammingServer Side Programming

A Constructor in C# is invoked automatically when an object gets created. The constructor has the same name as that of the class, for example −

public class Department {
   public Department () {
      Console.WriteLine("Default Constructor! ");
   }
}

The following is the code that shows the usage of default constructor in C#. The constructor invokes immediately when the object gets created.

Department dept1 = new Department ();

A default constructor is a constructor that has no argument, for example −

Department () {
}

Let us see the complete example to learn how to work with default contructors.

Example

 Live Demo

using System;
public class Department {
   public Department () {
      Console.WriteLine("Constructor Invoked");
   }
   public static void Main(string[] args) {
      // object
      Department dept1 = new Department ();
   }
}

Output

Constructor Invoked
raja
Published on 17-Sep-2018 11:49:20
Advertisements