C# | Constructors - GeeksforGeeks

05 Nov, 2020
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also 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. 
Example :  
class Geek
{   
  .......
  // Constructor
  public Geek() {}
  .......
}

// an object is created of Geek class,
// So above constructor is called
Geek obj = new Geek(); 


Constructor of a class must have the same name as the class name in which it resides.
A constructor can not be abstract, final, and Synchronized.
Within a class, you can create only one static constructor.
A constructor doesn’t have any return type, not even void.
A static constructor cannot be a parameterized constructor.
A class can have any number of constructors.
Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.  
Default ConstructorParameterized ConstructorCopy ConstructorPrivate ConstructorStatic Constructor
Default Constructor
Parameterized Constructor
Copy Constructor
Private Constructor
Static 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#
// C# Program to illustrate calling// a Default constructorusing System;namespace DefaultConstructorExample { class Geek {     int num;    string name;     // this would be invoked while the    // object of that class created.    Geek()    {        Console.WriteLine("Constructor Called");    }     // Main Method    public static void Main()    {         // this would invoke default        // constructor.        Geek geek1 = new Geek();         // Default constructor provides        // the default values to the        // int and object as 0, null        // Note:        // It Give Warning because        // Fields are not assign        Console.WriteLine(geek1.name);        Console.WriteLine(geek1.num);    }}}
Output : 
Constructor Called

0



Note : This will also show some warnings as follows: 
prog.cs(8, 6): warning CS0649: Field `DefaultConstructorExample.Geek.num' is never assigned to, and will always have its default value `0'
prog.cs(9, 9): warning CS0649: Field `DefaultConstructorExample.Geek.name' is never assigned to, and will always have its default value `null'

A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values.
Example :  
C#
// C# Program to illustrate calling of// parameterized constructor.using System;namespace ParameterizedConstructorExample { class Geek {     // data members of the class.    String name;    int id;     // parameterized constructor would    // initialized data members with    // the values of passed arguments    // while object of that class created.    Geek(String name, int id)    {        this.name = name;        this.id = id;    }     // Main Method    public static void Main()    {         // This will invoke parameterized        // constructor.        Geek geek1 = new Geek("GFG", 1);        Console.WriteLine("GeekName = " + geek1.name +                         " and GeekId = " + geek1.id);    }}}
Output : 
GeekName = GFG and GeekId = 1 

This constructor creates an object by copying variables from another object. Its main use is to initialize a new instance to the values of an existing instance. 
Example : 
C#
// C# Program to illustrate calling// a Copy constructorusing System;namespace copyConstructorExample { class Geeks {     private string month;    private int year;     // declaring Copy constructor    public Geeks(Geeks s)    {        month = s.month;        year = s.year;    }     // Instance constructor    public Geeks(string month, int year)    {        this.month = month;        this.year = year;    }     // Get details of Geeks    public string Details    {        get        {            return "Month: " + month.ToString() +                     "\nYear: " + year.ToString();        }    }     // Main Method    public static void Main()    {         // Create a new Geeks object.        Geeks g1 = new Geeks("June", 2018);         // here is g1 details is copied to g2.        Geeks g2 = new Geeks(g1);         Console.WriteLine(g2.Details);    }}}
Output : 
Month: June
Year: 2018


If a constructor is created with 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. 
Points To Remember :  
It is the implementation of a singleton class pattern.
use private constructor when we have only static members.
Using private constructor, prevents the creation of the instances of that class.
Example : 
C#
// C# Program to illustrate calling// a Private constructorusing System;namespace privateConstructorExample { public class Geeks {     // declare private Constructor    private Geeks()    {    }     // declare static variable field    public static int count_geeks;     // declare static method    public static int geeks_Count()    {        return ++count_geeks;    }     // Main Method    public static void Main()    {         // If you uncomment the following        // statement, it will generate        // an error because the constructor        // is unaccessible:        // Geeks s = new Geeks(); // Error         Geeks.count_geeks = 99;         // Accessing without any        // instance of the class        Geeks.geeks_Count();         Console.WriteLine(Geeks.count_geeks);         // Accessing without any        // instance of the class        Geeks.geeks_Count();         Console.WriteLine(Geeks.count_geeks);    }}}
Output : 
100
101


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 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 created.
Example :
C#
// C# Program to illustrate calling// a Static constructorusing System;namespace staticConstructorExample { class geeks {     // It is invoked before the first    // instance constructor is run.    static geeks()    {         // The following statement produces        // the first line of output,        // and the line occurs only once.        Console.WriteLine("Static Constructor");    }     // Instance constructor.    public geeks(int i)    {        Console.WriteLine("Instance Constructor " + i);    }     // Instance method.    public string geeks_detail(string name, int id)    {        return "Name:" + name + " id:" + id;    }     // Main Method    public static void Main()    {         // Here Both Static and instance        // constructors are invoked for        // first instance        geeks obj = new geeks(1);         Console.WriteLine(obj.geeks_detail("GFG", 1));         // Here only instance constructor        // will be invoked        geeks obj1 = new geeks(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



 
ashumsd7
an_analyst
dhiman_saab
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# | How to check whether a List contains a specified element
String.Split() Method in C# with Examples
C# | Arrays of Strings
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Delegates
Difference between Ref and Out keywords in C#
C# | Replace() Method