C# Constructors
A constructor is a special method that runs automatically when an object is created, typically used to initialize a new object's fields. A constructor has the same name as its class and no return type.
C# provides a default parameterless constructor automatically if you don't define one, but once you define any constructor, the default one is no longer generated automatically.
public ClassName(parameters) {
// initialization code
}Defining constructors
A constructor is written like a method with the class's name and no return type, like `public Car() { }`. It runs whenever `new Car()` is called.
Parameterized constructors
A constructor can accept parameters to set initial values, like `public Car(string color) { this.color = color; }`. The `this` keyword refers to the current object.
using System;
class Car {
public string color;
public Car(string color) {
this.color = color;
}
}
class Program {
static void Main() {
Car myCar = new Car("Blue");
Console.WriteLine(myCar.color);
}
}BlueThe constructor sets the color field when the Car object is created.
using System;
class Person {
public string Name { get; set; }
public Person() {
Name = "Unknown";
}
}
class Program {
static void Main() {
Person p = new Person();
Console.WriteLine(p.Name);
}
}UnknownThe parameterless constructor sets a default value for Name automatically.
Key points
- A constructor has the same name as its class and no return type.
- Constructors run automatically when an object is created with `new`.
- The `this` keyword refers to the current object's own members.
- Defining any constructor removes the automatic default constructor.
