C# Constructors
A constructor is a special method that runs automatically the moment you create an object from a class. Its job is to set up the object so it starts life in a valid, ready-to-use state. In this lesson you will learn how to write constructors, pass values into them, and let C# build a default one for you.
What is a constructor?
A constructor is a method that has the same name as the class and has no return type, not even void. C# calls it for you automatically whenever you use the new keyword. Because it runs first, it is the perfect place to give your fields their starting values.
A simple constructor
class Car
{
public string model;
// Constructor: same name as the class, no return type
public Car()
{
model = "Mustang";
}
}
class Program
{
static void Main()
{
Car myCar = new Car(); // The constructor runs here
Console.WriteLine(myCar.model); // Outputs: Mustang
}
}Notice that we never called Car() ourselves as a normal method. Writing new Car() is what triggers the constructor, and by the time the object is handed back to us, the model field already holds the value "Mustang".
Constructor parameters
Hard-coding every value inside the constructor is not very useful. Constructors can accept parameters, so each object you create can start with different data. This is the most common way to fill in an object's details.
Passing values into a constructor
class Car
{
public string model;
public string color;
public int year;
public Car(string modelName, string modelColor, int modelYear)
{
model = modelName;
color = modelColor;
year = modelYear;
}
}
class Program
{
static void Main()
{
Car car1 = new Car("Mustang", "Red", 1969);
Car car2 = new Car("Corvette", "Black", 2021);
Console.WriteLine($"{car1.color} {car1.year} {car1.model}");
Console.WriteLine($"{car2.color} {car2.year} {car2.model}");
}
}The default constructor
If you do not write any constructor at all, C# quietly supplies a hidden one that takes no arguments and does nothing special. This is called the default constructor, and it is why new Car() works even for a class with no visible constructor. As soon as you write your own constructor, that free default disappears.
Constructor quick facts
Constructors save you from creating an object and then setting every field on a separate line. Instead, one call to new can build a fully prepared object in a single, readable step.
Exercise: C# Constructors
What must the name of a C# constructor match?