Constructors in C#

CsharpProgrammingServer Side Programming

A Constructor in C# gets invoked automatically when a 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 constructor in C#.

Example

 Live Demo

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

Output

Constructor Invoked
raja
Published on 17-Sep-2018 08:14:02
Advertisements