When you create an object with new, something happens behind the scenes โ a special method called a constructor runs. Constructors set up your object so it's ready to use right away.
The Default Constructor
If you don't write a constructor, C# gives you one for free. It takes no parameters and does nothing โ it just creates the object. Fields are left at their default values (0, null, false, etc.).
class Car
{
public string brand;
public int year;
}
Car myCar = new Car();
Console.WriteLine(myCar.brand);
Console.WriteLine(myCar.year);
This prints (empty string / null) and 0.
Parameterized Constructors
Most of the time you want to set values at creation time. Write a constructor with parameters. It must have the same name as the class and no return type.
class Car
{
public string brand;
public int year;
public Car(string brand, int year)
{
this.brand = brand;
this.year = year;
}
}
Car myCar = new Car("Tesla", 2023);
Console.WriteLine(myCar.brand);
Console.WriteLine(myCar.year);
Try it Yourself โ
The this Keyword
When a parameter has the same name as a field, C# doesn't know which is which. Use this to refer to the current object's field. this.brand means "the brand that belongs to this object," while brand alone means the parameter.
public Car(string brand, int year)
{
this.brand = brand;
this.year = year;
}
You don't always need this โ only when there's a naming conflict. Many developers use it anyway for clarity.
Multiple Constructors
You can have more than one constructor, as long as their parameter lists differ. This is called overloading.
class Car
{
public string brand;
public int year;
public Car()
{
brand = "Unknown";
year = 2000;
}
public Car(string brand, int year)
{
this.brand = brand;
this.year = year;
}
}
Car unknown = new Car();
Console.WriteLine(unknown.brand);
Car known = new Car("BMW", 2021);
Console.WriteLine(known.brand);
Now you can create a Car with or without details โ handy when you don't have all the info yet.