c-sharp
  1. c-sharp-constructor

C# Constructor

Syntax

class ClassName
{
  access_modifier ClassName (parameter_list)
  {
    // Constructor code
  }
}

Example

class Car
{
    string model;
    int year;

    public Car(string modelName, int modelYear)
    {
        model = modelName;
        year = modelYear;
    }

    static void Main(string[] args)
    {
        Car myCar = new Car("Mustang", 1969);
        Console.WriteLine("Model: " + myCar.model + " Year: " + myCar.year);
    }
}

Output

Model: Mustang Year: 1969

Explanation

A constructor is a special method in a class that is called when an instance of the class is created. The purpose of a constructor is to initialize values for the object being created. Constructors can take parameters just like any other method.

In the example above, the Car class has a constructor that accepts two parameters, modelName and modelYear. The constructor sets the values of the model and year variables. The Main method creates a new Car object, passing in the values "Mustang" and 1969. The values are then displayed using the Console.WriteLine method.

Use

Constructors are used to initialize objects with default values or values passed in as parameters. They are commonly used in object-oriented programming to ensure that objects are properly initialized before they are used.

Important Points

  • Constructors have the same name as the class and no return type.
  • Constructors are called automatically when an object is created.
  • A constructor can have parameters to set initial values for an object.
  • Constructors can be used to enforce that objects are initialized properly.

Summary

Constructors are a critical part of object-oriented programming and are used to initialize objects with default values or values passed in as parameters. Constructors have the same name as the class and no return type, and they are called automatically when an object is created. A constructor can have parameters to set initial values for an object, and is used to enforce that objects are initialized properly.

Published on: