Constructors in C#



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
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements