C# Constructors

In the C# programming language, a constructor serves as a specialized method within a class, which is invoked automatically upon the creation of an instance of that class. It contains a series of commands executed during the object's instantiation. The primary purpose of a constructor is to set up the initial values of the class's attributes and ready the object for operation.

Constructors have several features in contrast to conventional methods in C#. Some of them are as follows:

  • The constructor class name should be the same as the class.
  • It has no return type.
  • When the new keyword is used to create an object, this function is automatically invoked.
  • It cannot be abstract and virtual.
  • Syntax of a Constructor

It has the following syntax:

Example

class Demo

{

    //Class name "Demo"

    // Constructor of "Demo" class.

    public Demo() 

  {

        // Initialization code write here

    }

}

Calling the Constructor

To invoke the constructor, we can utilize the syntax below:

Example

Demo d1 = new Demo();

// Demo constructor called and d1 object created.

C# Constructor Example

Let's consider a scenario to demonstrate the constructor in C#.

Example

Example

using System;

class Employee

{

    // Fields

    public string Name;

    public int Age;

    public int Salary;

    // Constructor

    public Employee(string name, int age, int salary)

    {

        Name = name;

        Age = age;

        Salary = salary;

    }

    // Method to display employee details

    public void DisplayInfo()

    {

        Console.WriteLine("Employee Name: " + Name);

        Console.WriteLine("Employee Age: " + Age);

        Console.WriteLine("Employee Salary: " + Salary);

    }

}

class Program

{

    static void Main()

    {

        // Creating object and calling constructor

        Employee emp1 = new Employee("Jhonson", 25, 45000);

        emp1.DisplayInfo();

    }

}

Output:

Output

Employee Name: Jhonson

Employee Age: 25

Employee Salary: 45000

Explanation:

In this instance, we are considering the constructor Employee(string name, int age, int salary) which is used to set the values for Name, Age, and Salary during object instantiation. Subsequently, the emp1 instance is assigned particular data, and the DisplayInfo function showcases the employee's information.

Important Points to Remember About Constructors in C#

There are several points to remember about a constructor in C#. Some of them are as follows:

  • Same Name as Class: The constructor must have the same name as the class where it is defined.
  • Automatic Invocation: It is called automatically when an object is formed using a new keyword.
  • Overloading is permitted: A class may have numerous constructors, each contains a different set of parameters.
  • Access Modifiers Allowed: Constructors can be declared with access modifiers, which control who can construct objects from that class.
  • Static Constructor Rules: A class can have only one static constructor, which is used to initialize static members. It only runs once during the entire class.
  • If no constructors are defined: If no constructor is explicitly defined, the C# compiler will create a default parameterless constructor.
  • Types of Constructors

There are primarily five categories of constructors in C#. These include:

The CSS code snippet below defines a placeholder diagram with a gradient background, rounded corners, padding, margin, and center-aligned text. The placeholder icon is styled with a specific font size and margin, while the placeholder text color and font size are also specified.

Next, we will examine each of these constructors individually.

Default Constructor

In C# programming, a default constructor is parameterless. If no other constructors are defined in the class, the compiler generates a default constructor automatically. This constructor is primarily used to assign default or constant values to objects.

Features of the Default Constructor:

There are several features of the default constructor. Some of them are as follows:

  • It doesn't require any parameters.
  • When a new object is created, this function is automatically invoked.
  • It can be defined explicitly.
  • C# Default Constructor Example

Let's consider an example to demonstrate the default constructor in C#.

Example

Example

using System;

class Student

{

    public string stu_Name;

    // Default Constructor called.

    public Student()

    {

        stu_Name = "Joseph";

    }

    static void Main()

    {

        Student s = new Student();

        Console.WriteLine("The name of the student is: " + s.stu_Name);

    }

}

Output:

Output

The name of the student is: Joseph

Explanation:

When an instance is generated in this scenario, the Student constructor is automatically called with "Joseph" as the default name. This constructor doesn't need any arguments and is responsible for initializing predefined initial values to the class attributes.

Parameterized Constructor

In C#, a parameterized constructor is a special type of constructor that requires a minimum of one parameter to set specific values for an object when it is being created. This constructor receives arguments and then assigns these values to the corresponding class fields.

Features of Parameterized Constructor:

Some characteristics of parameterized constructor in C# include:

  • It provides increased versatility during object initialization.
  • Constructor overloading facilitates the development of several parameterized constructors.
  • C# Parameterized Constructor Example

Let's consider an illustration to demonstrate the parameterized constructor in C#.

Example

Example

using System;

class Student

{

    public string name;

    public int age;

    // Parameterized Constructor called.

    public Student(string student_Name, int student_Age)

    {

        name = student_Name;

        age = student_Age;

    }

    static void Main()

    {

        Student stu = new Student("Joseph", 26);

        Console.WriteLine("The name of the student is: " + stu.name);

        Console.WriteLine("The age of the student is: " + stu.age);

    }

}

Output:

Output

The name of the student is: Joseph

The age of the student is: 26

Explanation:

In this instance, we are examining a constructor within the Student class that takes parameters for names, ages, and fields. These parameters are then set to the values provided when the object is instantiated. This feature facilitates the ability to initialize objects dynamically with either predefined or real-time data.

Copy Constructor

A duplication constructor creates a fresh instance by replicating the data from an existing object. Unlike C++, C# does not come equipped with a pre-existing duplication constructor. In scenarios where object replication is necessary, developers can craft a duplication constructor manually.

Features of the Copy Constructor:

Several features of the copy constructor in C# are as follows:

  • It takes an object of the same class as a parameter to copy its data.
  • When deep copying is necessary, it is extremely useful.
  • C# Copy Constructor Example

Let's consider a scenario to demonstrate the copy constructor in C#.

Example

Example

using System;

class Car

{

    public string name;

    // Parameterized Constructor called.

    public Car(string n)

    {

        name = n;

    }

    // Copy Constructor called.

    public Car(Car c)

    {

        name = c.name;

    }

    static void Main()

    {

        Car car1 = new Car("TATA");

        Car car2 = new Car(car1);

        Console.WriteLine("The Original name of the Car is: " + car1.name);

        Console.WriteLine("The Copy name of the Car is: " + car2.name);

    }

}

Output:

Output

The Original name of the Car is: TATA

The Copy name of the Car is: TATA

Explanation:

In this instance, we illustrate the functionality of a copy constructor, responsible for generating a fresh instance (car2) through replicating the attributes of an already existing object (car1). Following this, the Car class is equipped with a parameterized constructor for setting up the object and a copy constructor that mirrors the content of the name field.

Static Constructor

In C#, a static constructor is primarily employed to set up static data members within a class. It runs automatically just once, prior to the creation of any instances or accessing static members, guaranteeing the proper initialization of static fields.

Features of the Static Constructor:

Several features of the static constructor in C# are as follows:

  • There are no acceptable parameters.
  • It cannot be invoked explicitly.
  • There are no access modifiers utilized.
  • C# Static Constructor Example

Let's consider an example to demonstrate the static constructor in C#.

Example

Example

using System;

class Database

{

    public static string connection;

    // Static Constructor called.

    static Database()

    {

        connection = "Connected to DB";

        Console.WriteLine("Static constructor block executed");

    }

    static void Main()

    {

        Console.WriteLine(Database.connection);

    }

}

Output:

Output

Static constructor block executed

Connected to DB

Explanation:

In this instance, the static constructor is invoked automatically prior to the creation of any objects or accessing static fields. The static connection attribute is set up at this point, and a notification is displayed upon the initial loading of the class.

Private Constructor

In C# programming, a private constructor prevents external classes from creating objects of that class. This practice is commonly applied in Singleton Design Patterns and utility classes.

Features of Private Constructor:

Several characteristics of the private constructor in C# include:

  • It serves to restrict object instantiation from external sources.
  • It is appropriate for classes that are solely static or singleton instances.
  • C# Private Constructor Example

Let's consider an example to demonstrate the private constructor concept in C#.

Example

Example

using System;

class Logger

{

    private Logger() { }

    public static void Log(string message)

    {

        Console.WriteLine("Log: " + message);

    }

    static void Main()

    {

        Logger.Log("App started");

        Logger obj = new Logger();    //Compile-time error

    }

}

Output:

Output

Log: App started

Explanation:

In this instance, we've implemented a private constructor to restrict object creation external to the class, a crucial aspect in patterns like Singleton. Although the Logger.Log function remains functional, attempting direct instantiation (new Logger) leads to a compile-time error.

Constructor Overloading

In C#, constructor overloading in a class allows for the creation of multiple constructors with different parameter lists. This feature permits the instantiation of objects in different ways based on the available information during object creation.

Features of Constructor Overloading:

Several features of constructor overloading in C# are as follows:

  • Every constructor must have the same name as the class.
  • Constructors differ in terms of the number and kind of parameters.
  • The correct constructor is selected automatically based on the inputs supplied.
  • Constructor Overloading Example in C#

Let's consider a scenario to demonstrate constructor overloading in C#.

Example

Example

using System;

namespace ConstructorOverloadExample

{

    class Book

    {

        // Constructor with no parameters.

        public Book()

        {

            Console.WriteLine("The Default constructor is called");

        }

        // Constructor with one parameter.

        public Book(string Book_Title)

        {

            Console.WriteLine("The title of the book is: " + Book_Title);

        }

        // Constructor with two parameters.

        public Book(string Book_Title, string Author_Name)

        {

            Console.WriteLine("The title of the book is: " + Book_Title);

            Console.WriteLine("The name of the Author is: " + Author_Name);

        }

        static void Main(string[] args)

        {

            // Calls default constructor

            Book bk1 = new Book();

            Console.WriteLine();

            // Calls the constructor with one parameter

            Book bk2 = new Book("Python");

            Console.WriteLine();

            // Calls the constructor with two parameters

            Book bk3 = new Book("C# Programming", "Jamie Chan");

            Console.ReadLine();

        }

    }

}

Output:

Output

The Default constructor is called

The title of the book is: Python

The title of the book is: C# Programming

The name of the Author is: Jamie Chan

Explanation:

In this instance, we are examining a Book class showcasing multiple constructors with different argument combinations, allowing for more flexible object creation. The appropriate constructor is selected based on the provided inputs, showcasing how overloading enhances usability.

Usage of Constructors in C#

There are several uses of the constructor in C#. Some of them are as follows:

  • When an object is created, it is automatically initialized.
  • It assigns class fields with default or custom values.
  • It allows for constructor overloading for greater flexibility.
  • Static constructors are mainly utilized to set up static members.
  • Using private constructors, we can restrict object creation.
  • Design patterns such as Singleton should be supported.
  • Clean initialization helps to improve code readability and maintainability.
  • Conclusion

In summary, constructors play a crucial role in C# as they are employed to set up objects during class instance creation. They offer flexibility by enabling default setup, providing customized values, copying information, restricting object creation, and initializing static data. Constructor overloading enhances object creation by enabling multiple initialization options. In essence, constructors are vital for controlling the setup and behavior of objects right from their inception.

C# Constructor FAQs

1) What is a constructor in C#?

In C#, a constructor is a specialized method within a class that is automatically called upon object instantiation to initialize the object. It establishes the initial state of the object.

Yes, in C#, it is feasible for a class to possess multiple constructors.

Yes, through constructor overloading, a class can contain multiple constructors with different parameter lists.

In C#, the distinction between default and parameterized constructors lies in their initialization behavior. While a default constructor is automatically provided by the compiler if no constructor is defined, a parameterized constructor requires parameters to be specified during object creation.

A default constructor does not receive any arguments, while a parameterized constructor does take in values to initialize fields.

4) Can a constructor be designated as private in C#?

Yes, a private constructor is primarily used in singleton patterns to restrict object instantiation from external sources.

5) When does a static constructor function run?

When a class is first accessed, a static constructor is automatically called prior to any instances being instantiated.

Input Required

This code uses input(). Please provide values below: