C# Constructor

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

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:

Task:

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.

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.

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.