A constructor is a special method that is used to initialize objects. The advantage of a constructor is that it is called automatically when an object of a class is created.
It is commonly used to set initial values for fields.
To create a constructor, you must follow these two rules:
void or int).using System;class Car { public string model; // Create a field
// Create a class constructor for the Car class public Car() { model = "Mustang"; // Set the initial value for model }
static void Main(string[] args) { // This automatically calls the constructor! Car Ford = new Car(); Console.WriteLine(Ford.model); // Outputs "Mustang" } }
Constructors can also take parameters, which is very useful for setting initial values based on specific input when the object is created.
using System;class Car { public string model; public string color; public int year;
// Constructor with parameters public Car(string modelName, string modelColor, int modelYear) { model = modelName; color = modelColor; year = modelYear; }
static void Main(string[] args) { // Passing values to the constructor Car Ford = new Car("Mustang", "Red", 1969); Car Opel = new Car("Astra", "White", 2005); Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model); Console.WriteLine(Opel.color + " " + Opel.year + " " + Opel.model); } }
By passing values directly into new Car(...), we save time and write much cleaner code compared to initializing each field manually after object creation!
Did you know? If you do not create a constructor in your class, C# automatically creates a default, empty constructor for you.
What is a key rule for naming a constructor in C#?