C# Constructors
A constructor is a special method that runs when an object is created. It sets the starting values of the new object.
A constructor sets a field
The Car constructor takes one value. It stores that value in the model field.
using System;
class Car
{
public string model;
public Car(string modelName)
{
model = modelName;
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car("Ford");
Console.WriteLine(myCar.model);
}
}Two parameters
This constructor takes two values. It stores one value in each field.
using System;
class Car
{
public string model;
public int year;
public Car(string modelName, int carYear)
{
model = modelName;
year = carYear;
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car("Ford", 2020);
Console.WriteLine(myCar.model);
Console.WriteLine(myCar.year);
}
}Two constructors, one class
Car has two constructors. The call with no value runs the first one.
using System;
class Car
{
public string model;
public Car()
{
model = "Unknown";
}
public Car(string modelName)
{
model = modelName;
}
}
class Program
{
static void Main(string[] args)
{
Car firstCar = new Car();
Car secondCar = new Car("BMW");
Console.WriteLine(firstCar.model);
Console.WriteLine(secondCar.model);
}
}Example
using System;
class Student
{
public string name;
public int grade;
public Student(string studentName, int studentGrade)
{
name = studentName;
grade = studentGrade;
}
}
class Program
{
static void Main(string[] args)
{
Student student = new Student("Hana", 9);
Console.WriteLine(student.name + " is in grade " + student.grade + ".");
}
}Key points
- A constructor has the same name as its class.
- A constructor has no return type.
- The constructor runs at the moment new creates the object.
- Parameters pass starting values into the new object.
- A class can hold more than one constructor.
- Each constructor in a set needs a different parameter list.
In this example, the Student constructor takes a name and a grade. It stores Hana in the name field. It stores 9 in the grade field. The last line joins the two fields into one sentence.
Note
A constructor runs only once for each object.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
When does a constructor run?