Lesson 31 +10 XP

Constructors

Constructors

A constructor is a special method that runs automatically when an object is created. It's perfect for setting initial values.

A constructor

A constructor has the same name as the class and no return type (not even void):

class Car
{
  public string model;

  // Constructor
  public Car()
  {
    model = "Mustang";
  }

  static void Main(string[] args)
  {
    Car Ford = new Car();
    Console.WriteLine(Ford.model);   // Mustang
  }
}

Constructors with parameters

Constructors can take parameters to set values per object:

class Car
{
  public string model;

  public Car(string modelName)
  {
    model = modelName;
  }

  static void Main(string[] args)
  {
    Car Ford = new Car("Mustang");
    Car Opel = new Car("Opel");
    Console.WriteLine(Ford.model);   // Mustang
    Console.WriteLine(Opel.model);   // Opel
  }
}

Multiple constructors (overloading)

Like methods, constructors can be overloaded with different parameters.

Why use constructors?

  • They run automatically - no forgetting to initialize.
  • They force an object to start in a valid state.
  • Parameters let each object start differently.

TL;DR

  • A constructor runs automatically when new is used.
  • It has the class's name and no return type.
  • Parameterized constructors set custom starting values.
  • Constructors can be overloaded.