A constructor in C# is a special method of a class that is automatically called when an object of the class is created. It has the same name as the class, does not have a return type and is mainly used to initialize the object’s data members.
- A class can define multiple constructors (constructor overloading).
- A constructor cannot be virtual or abstract. Only a special kind of constructor can be static.
Example:
class Geeks{
// constructor of Geeks class
public Geeks( ) { }
}
// Using this constructor
Geeks obj = new Geeks();
Types of Constructor
Common constructor types are:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Private Constructor
- Static Constructor
1. Default Constructor
A default constructor in C# is a constructor with no parameters. It is automatically provided by the compiler if no constructor is defined in the class. It initializes numeric fields to 0, Boolean to false and reference types like strings or objects to null.
Example:
C#
using System;
class Geeks {
// Fields without manual initialization
int num; // default: 0
string name; // default: null
bool flag; // default: false
// Default constructor
public Geeks() {
Console.WriteLine("Constructor Called");
}
public static void Main() {
// Invoke default constructor
Geeks geek1 = new Geeks();
// Display default values of fields
Console.WriteLine("num = " + geek1.num);
Console.WriteLine("name = " + geek1.name);
Console.WriteLine("flag = " + geek1.flag);
}
}
Note: The compiler may show warnings since the fields are never explicitly assigned. These warnings are safe to ignore here because they illustrate the default values assigned automatically by C#.
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#
using System;
class Geek {
// store name value
String n;
// store Id
int i;
// the values of passed arguments while object of that class created.
Geek(String n, int i){
this.n = n;
this.i = i;
}
public static void Main(){
// It will invoke parameterized
Geek o = new Geek("GFG", 1);
Console.WriteLine("Name = " + o.n + " Id = " + o.i);
}
}
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#
using System;
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();
}
}
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);
}
}
OutputMonth: June
Year: 2018
Note:
C# does not have a predefined copy constructor, we manually create one if needed.
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#
using System;
public class Geeks
{
// private Constructor
private Geeks()
{
Console.WriteLine("from private constructor");
}
public static int count_geeks;
public static int geeks_Count()
{
return ++count_geeks;
}
public static void Main()
{
// This will cause an error (private constructor), Geeks s = new Geeks();
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);
}
}
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.
- 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#
using System;
class Geeks
{
// It is invoked before the first instance constructor is run.
static Geeks()
{
Console.WriteLine("Static Constructor");
}
public Geeks(int i)
{
Console.WriteLine("Instance Constructor " + i);
}
public string geeks_detail(string name, int id)
{
return "Name: " + name + " id: " + id;
}
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));
Geeks obj1 = new Geeks(2);
Console.WriteLine(
obj1.geeks_detail("GeeksforGeeks", 2));
}
}
OutputStatic Constructor
Instance Constructor 1
Name: GFG id: 1
Instance Constructor 2
Name: GeeksforGeeks id: 2
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers