C# ยท Chapter 31 of 46

C# Constructors

A constructor is a special method that runs automatically when an object is created, typically used to initialize a new object's fields. A constructor has the same name as its class and no return type.

C# provides a default parameterless constructor automatically if you don't define one, but once you define any constructor, the default one is no longer generated automatically.

Syntax
public ClassName(parameters) {
  // initialization code
}

Defining constructors

A constructor is written like a method with the class's name and no return type, like `public Car() { }`. It runs whenever `new Car()` is called.

Parameterized constructors

A constructor can accept parameters to set initial values, like `public Car(string color) { this.color = color; }`. The `this` keyword refers to the current object.

Example 1 (csharp)
using System;

class Car {
  public string color;
  public Car(string color) {
    this.color = color;
  }
}

class Program {
  static void Main() {
    Car myCar = new Car("Blue");
    Console.WriteLine(myCar.color);
  }
}
Output
Blue

The constructor sets the color field when the Car object is created.

Example 2 (csharp)
using System;

class Person {
  public string Name { get; set; }
  public Person() {
    Name = "Unknown";
  }
}

class Program {
  static void Main() {
    Person p = new Person();
    Console.WriteLine(p.Name);
  }
}
Output
Unknown

The parameterless constructor sets a default value for Name automatically.

Key points

  • A constructor has the same name as its class and no return type.
  • Constructors run automatically when an object is created with `new`.
  • The `this` keyword refers to the current object's own members.
  • Defining any constructor removes the automatic default constructor.
๐Ÿ’ก Note: A class can have multiple constructors (constructor overloading) with different parameter lists.

๐Ÿ“ Quick Quiz

1. What is the return type of a constructor?

2. When does a constructor run?

3. What does the `this` keyword refer to?