Open In App

C# Constructors

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Constructors in C# are fundamental components of object-oriented programming. Like methods, It contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class. Some important points about Constructors are mentioned below:

  • The constructor of a class must have the same name as the class name in which it resides.
  • A class can have any number of constructors.
  • A constructor can not be abstract, final, and Synchronized.
  • A constructor doesn’t have any return type.

Example:

class Geeks{
// constructor of Geeks class
public Geeks( ) { }
}

// Using of this constructor
Geeks obj = new Geeks();

Types of Constructor

There are different types of constructors in C#, each serving different purposes. These are the most commonly used:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Private Constructor
  5. Static Constructor

1. Default Constructor

A constructor with no parameters is called a Default constructor. A default constructor has every instance of the class to be initialized to the same values. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class.

Example:

C#
// Default constructorusingSystem;classGeeks{// Initialize with default valueintnum=0;// Initialize with an empty stringstringname="";publicGeeks(){Console.WriteLine("Constructor Called");}publicstaticvoidMain(){// Invoke default constructorGeeksgeek1=newGeeks();// Display default values of fieldsConsole.WriteLine(geek1.name);Console.WriteLine(geek1.num);}}

Output
Constructor Called 0 

2. Parameterized Constructor

A constructor having at least one parameter is called a parameterized constructor. It can initialize each instance of the class to different values.

Example:

C#
// Parameterized ConstructorusingSystem;classGeek{// store name valueStringn;// store Idinti;// the values of passed arguments// while object of that class created.Geek(Stringn,inti){this.n=n;this.i=i;}publicstaticvoidMain(){// It will invoke parameterizedGeeko=newGeek("GFG",1);Console.WriteLine("Name = "+o.n+" Id = "+o.i);}}

Output
Name = GFG Id = 1 

3. Copy Constructor

A copy constructor is used to create a new object by copying the values from an existing object of the same class. Useful when you need to duplicate an object or create a new object based on the state of another.

Example:

C#
// Copy constructorusingSystem;classGeeks{privatestringmonth;privateintyear;// declaring Copy constructorpublicGeeks(Geekss){month=s.month;year=s.year;}// Instance constructorpublicGeeks(stringmonth,intyear){this.month=month;this.year=year;}// Get details of GeekspublicstringDetails{get{return"Month: "+month.ToString()+"\nYear: "+year.ToString();}}publicstaticvoidMain(){// Create a new Geeks object.Geeksg1=newGeeks("June",2018);// here is g1 details is copied to g2.Geeksg2=newGeeks(g1);Console.WriteLine(g2.Details);}}

Output
Month: June Year: 2018 

4. Private Constructor

If a constructor is created with a private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class. Some important points regarding the topic is mentioned below:

  • It is the implementation of a singleton class pattern.
  • Use a private constructor when we have only static members.
  • Using a private constructor prevents the creation of the instances of that class.

Note: Access modifiers can be used in constructor declaration to control its access i.e. which other class can call the constructor. Private Constructor is one of it’s example.

Example

C#
// Private constructorusingSystem;publicclassGeeks{// private ConstructorprivateGeeks(){Console.WriteLine("from private constructor");}publicstaticintcount_geeks;publicstaticintgeeks_Count(){return++count_geeks;}publicstaticvoidMain(){// If you uncomment the following// statement, it will generate// an error because the constructor// is unaccessible:// Geeks s = new Geeks(); // ErrorGeeks.count_geeks=99;// Accessing without any// instance of the classGeeks.geeks_Count();Console.WriteLine(Geeks.count_geeks);// Accessing without any// instance of the classGeeks.geeks_Count();Console.WriteLine(Geeks.count_geeks);}}

Output
100 101 

5. Static Constructor

Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and is to be executed only once.

Points To Remember:

  • It can’t be called directly.
  • When it is executing then the user has no control.
  • It does not take access modifiers or any parameters.
  • It is called automatically to initialize the class before the first instance is created.

Example:

C#
// Static constructorusingSystem;classGeeks{// It is invoked before the first// instance constructor is run.staticGeeks(){Console.WriteLine("Static Constructor");}publicGeeks(inti){Console.WriteLine("Instance Constructor "+i);}publicstringgeeks_detail(stringname,intid){return"Name: "+name+" id: "+id;}publicstaticvoidMain(){// Here Both Static and instance// constructors are invoked for// first instanceGeeksobj=newGeeks(1);Console.WriteLine(obj.geeks_detail("GFG",1));Geeksobj1=newGeeks(2);Console.WriteLine(obj1.geeks_detail("GeeksforGeeks",2));}}

Output
Static Constructor Instance Constructor 1 Name: GFG id: 1 Instance Constructor 2 Name: GeeksforGeeks id: 2 



Next Article
Article Tags :

Similar Reads

close