C# Constructor

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

Constructor

In C#, a constructor is a special type of method that is automatically called when an instance of a class is created. It is used to initialize the newly created object by setting initial values for its fields or performing any other necessary setup tasks also Constructor has the same name as the class name.

Syntax: In C#, constructors do not have a return type, not even void. They are declared using the public or private access modifier followed by the class name, and they may include parameters.

Basic Structure :

class ClassName

    {

        // Constructor definition

        public ClassName()

        {

            // Constructor body

            // Initialization code goes here

        }

    }

Default Constructor

using System;

class Car

{

    public string Make;

    public string Model;

    public int Year;

    // Default constructor

    public Car()

    {

        Make = “BMW”;

        Model = “M4”;

        Year = 2004;

    }

}

class Program

{

    static void Main(string[] args)

    {

        // Creating an object using the default constructor

        Car DefaultConstructor = new Car();

 

        // Displaying information about the car

        Console.WriteLine(“Default Constructor:”);

        DisplayCarInfo(DefaultConstructor);

    }

    static void DisplayCarInfo(Car car)

    {

        Console.WriteLine($”Make: {car.Make}, Model: {car.Model}, Year: {car.Year}”);

    }

}

Output: Default Constructor:
Make: BMW, Model: M4, Year: 2004

Static Constructor

using System;

class MyClass

{

    // Static field

    public static int StaticField;

    // Static constructor

    static MyClass()

    {

        Console.WriteLine(“Static constructor called.”);

        StaticField = 10; // Initializing the static field

    }

}

class Program

{

    static void Main(string[] args)

    {

        // Accessing the static field triggers the static constructor

        Console.WriteLine($”StaticField value: {MyClass.StaticField}”);

    }

}

Output: Static constructor called.
StaticField value: 10

Instance Constructor

using System;

class Car

{

    // Instance fields

    public string Make;

    public string Model;

    public int Year;

    // Instance constructor

    public Car(string make, string model, int year)

    {

        Make = make;

        Model = model;

        Year = year;

        Console.WriteLine(“Instance constructor called.”);

    }

}

class Program

{

    static void Main(string[] args)

    {

        // Creating an object of the Car class using the instance constructor

        Car myCar = new Car(“Toyota”, “Camry”, 2022);

        // Accessing the fields of the car object

        Console.WriteLine($”Make: {myCar.Make}, Model: {myCar.Model}, Year: {myCar.Year}”);

    }

}

Output: Instance constructor called.
Make: Toyota, Model: Camry, Year: 2022

Private Constructor

using System;

class Car

{

    public string Make { get; }

    public string Model { get; }

    public int Year { get; }

    // Private constructor to prevent direct instantiation

    private Car(string make, string model, int year)

    {

        Make = make;

        Model = model;

        Year = year;

    }

    // Static method to create a new Car instance

    public static Car CreateCar(string make, string model, int year)

    {

        // Validation can be added here if needed

        return new Car(make, model, year);

    }

    // Method to display car information

    public void DisplayCarInfo()

    {

        Console.WriteLine($”Make: {Make}, Model: {Model}, Year: {Year}”);

    }

}

class Program

{

    static void Main(string[] args)

    {

        // Create a Car instance using the static method

        Car myCar = Car.CreateCar(“Toyota”, “Camry”, 2022);

        // Display car information

        myCar.DisplayCarInfo();

    }

}

Output: Make: Toyota, Model: Camry, Year: 2022

Program To Practice:
1)Practice creating static constructors and instance constructors to calculate the division and multiplication of numbers entered at run time.
2)Write a C# program to add using Reference Parameters.

Practices Tasks

1. Imagine you are developing a software application for managing a library system. How would you use a static constructor to initialize a static data structure (e.g., a list of available books) that is shared across all instances of a Library class?

2. You are developing a healthcare application for scheduling patient appointments, you can use instance constructors in an Appointment class to initialize important properties like PatientName, DoctorName, AppointmentDate, and Location when patients book appointments online. 

For example: You have to create a class with name as Appointment with properties PatientName, DoctorName, AppointmentDate, and Location then create a instance constructor to initialize appointment details. create method to display appointment details. in main method create a new appointment and then create a new object using instance constructer of appointment class with passing parameter and then display appointment details using the display method your output should like below.