Constructor is a special method that gets called automatically when an object is created. It's commonly used to initialize values as soon as an object comes into existence. The constructor's name must match the class name, and it has no return type.
csharp
class Car
{
public string Model;
public int Year;
public Car(string model, int year)
{
Model = model;
Year = year;
}
public void ShowInfo()
{
Console.WriteLine($"{Year} {Model}");
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car("Mustang", 2024);
myCar.ShowInfo();
}
}What the constructor is for
new Car("Mustang", 2024)is called, the constructor takes two parameters.ModelandYearget their values set right when the object is created.- The constructor saves you from that classic mistake of creating an object and then forgetting to fill in its values afterward.
You should see
2024 Mustang