C# Constructor

Constructor

A constructor is like a special function inside the blueprint (class) that gets called when you create a new object based on that blueprint.

Note:  that the constructor’s name must match the class name, and it cannot have a return type (like void or int).
Also, note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, C# creates one for you. However, then you are not able to set initial values for fields.

Constructors save time! Take a look at the last example on this page to understand why.

Basic Structure :

class ClassName
    {
        // Constructor definition
        public ClassName()
        {
            // Constructor body
            // Initialization code goes here
        }
    }

Constructors can also take parameters, which are used to initialize fields.

The following example adds a string modelname and string colorname parameter to the constructor. Inside the constructor, we set the Model to modelname (Model=modelname) and colorname (Color=colorname). When we call the constructor, we pass a parameter to the constructor from object car1(“Toyota”, “Blue”), which will set the value of the Model to “Toyota” and Color to “Blue” and second object car2 (”BMW”, “Red”), which set the value of the Model to “BMW” and Color to “Red”

using System;
class Car
{
    public string Model;
    public string Color;
    public Car(string modelname, string colorname)
    {
        Model = modelname;
        Color = colorname;
    }
    public void Drive()
    {
        Console.WriteLine(“The “+ Color + ” ” + Model +” car is driving…”);
    }
}
class Program
{
    static void Main()
    {
        Car car1 = new Car(“Toyota”, “Blue”);
        Car car2 = new Car(“BMW”, “Red”);
        car1.Drive();
        car2.Drive();
    }
}

Output:

The Blue Toyota car is driving…
The Red BMW car is driving…

Explanation:

In the class car, we defined the first 2 fields as a string type to set the Model and Color

public string Model;
public string Color;

Then we create a constructor to get parameter values from the object to set the values in Model and Color

public Car(string modelname, string colorname)
{
   Model = modelname;
   Color = colorname;
}

after creating construction, we create a custom function named Drive where we print Model and Color values  in the console

public void Drive()
{
  Console.WriteLine(“The “+ Color + ” ” + Model +” car is driving…”);
}

Then we create a new program class where we call the main method which is the entry point for the program execution, and we create an object (instances)of the Car class and pass parameter in it to set values of  Model and Color in Constructor and then call the custom function named as Drive to print the Model & Color values in console.

class Program
{
    static void Main()
    {
        Car car1 = new Car(“Toyota”, “Blue”);
        Car car2 = new Car(“BMW”, “Red”);
        car1.Drive();
        car2.Drive();
    }
}

Constructors Save Time

When you consider the example from the previous chapter, you will notice that constructors are very useful, as they help reduce the amount of code:

Course Video
Course Video In English

Task:

1. Basic Constructor:
Create a class named Employee with the following properties:
string Name
int Id
double Salary
Implement a constructor that initializes these properties.
Create an object of the Employee class in the main method, initialize it using the constructor, and print the properties to the console.

2. Parameterized Constructor:
Create a class named Product with the following properties:
string ProductName
string Category
double Price
Implement a parameterized constructor that takes arguments to initialize these properties.
Create an object of the Product class in the main method, initialize it using the parameterized constructor, and print the properties to the console.

3. Default and Parameterized Constructor:
Create a class named Student with the following properties:
string Name
int RollNumber
string Course
Implement a default constructor that initializes these properties with default values.
Implement a parameterized constructor that takes arguments to initialize these properties.
Create objects using both constructors in the main method and print the properties to the console.

Frequently Asked Questions

Still have a question?

Let's talk

A constructor is a special method in a class used to initialize objects. It has the same name as the class and is automatically invoked when an object is created.

Unlike a method, a constructor does not have a return type, not even void, and is automatically called when an object is instantiated.

C# supports several types of constructors, including:

  • Default constructor
  • Parameterized constructor
  • Static constructor
  • Copy constructor

A default constructor has no parameters and is used to initialize an object with default values. If no constructor is defined, C# provides a default constructor automatically.

A parameterized constructor accepts arguments and is used to initialize an object with specific values provided during creation.

A static constructor is called once for all instances of a class. It initializes static fields and is executed automatically when the class is accessed for the first time.

Yes, constructors can be overloaded by defining multiple constructors with different parameters within the same class.

A copy constructor creates a new object as a copy of an existing object. It is usually implemented manually in C# by accepting an object as a parameter.

Yes, this is known as constructor chaining. It is done using the this or base keyword to call another constructor in the same or base class, respectively.

Constructors ensure proper initialization of an object before it is used, improving code safety and readability by encapsulating setup logic.

You can find free video tutorials in Hindi on constructors in C# at Iqra Academy, covering syntax and examples for beginners.

Yes, Iqra Academy offers free Hindi video tutorials that explain default constructors in C# with clear examples.

Constructors are essential for initializing objects, setting default values, and ensuring that class fields are properly configured when an object is created.

Absolutely! Free online tutorials at Iqra Academy provide step-by-step guidance with examples and exercises on constructors in C#.