A constructor is a special method in a class that is automatically called when an object of the class is created. It is used to initialize objects.
A constructor has the same name as the class and does not have a return type (not even void
).
class Car
{
public string brand;
// Constructor
public Car()
{
brand = "Default Brand";
Console.WriteLine("Constructor called!");
}
}
When an object is created, the constructor is automatically called:
class Program
{
static void Main()
{
Car myCar = new Car(); // Constructor runs here
Console.WriteLine(myCar.brand); // Output: Default Brand
}
}
Constructors can also take parameters to initialize fields with custom values.
class Car
{
public string brand;
// Constructor with parameter
public Car(string carBrand)
{
brand = carBrand;
}
}
class Program
{
static void Main()
{
Car car1 = new Car("Honda");
Car car2 = new Car("Toyota");
Console.WriteLine(car1.brand); // Output: Honda
Console.WriteLine(car2.brand); // Output: Toyota
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!