C#
Parameterized constructor
Learn to initialize objects with parameterized constructors.
Parameterized constructor
Constructors can take parameters. This way you can pass initial values from outside when creating the object: public Car(string make) { Make = make; }.
The call also has parameters: new Car("Toyota"). Here "Toyota" is passed to the constructor as make and assigned to the Make property. A parameterized constructor puts the object into a valid state the moment it is created; no separate assignment lines are needed.
Multiple parameters
A constructor can take multiple parameters separated by commas: public Car(string make, string model, int year). The call gives values in the same order: new Car("Toyota", "Corolla", 2020).
Order matters: the first value goes to make, the second to model, the third to year. Wrong order sends wrong values. In constructors with many parameters, meaningful names prevent confusion.
Exercise Add a parameterized constructor to Car
Add public string Make { get; set; }, public string Model { get; set; } and public int Year { get; set; } properties to the Car class. Then declare a three-parameter constructor that assigns each parameter to its property. Inside Main create an instance with new Car("Toyota", "Corolla", 2020) and print Make.
Show example solution
Define three properties and a three-parameter constructor. In Main write Car c = new Car("Toyota", "Corolla", 2020); Console.WriteLine(c.Make);
Example solution:
using System;
class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public Car(string make, string model, int year)
{
Make = make;
Model = model;
Year = year;
}
}
class Program
{
static void Main()
{
Car c = new Car("Toyota", "Corolla", 2020);
Console.WriteLine(c.Make);
}
}
Test yourself
-
Complete the parameter declaration
public Car(string ____) { Make = make; }
Show answer
public Car(string make) { Make = make; }
-
Which is a parameterized constructor call?
public Car(string make, string model, int year) { ... }
- new Car("Toyota", "Corolla", 2020)
- new Car()
- new Car[]
- Car()
Show answer
new Car("Toyota", "Corolla", 2020) — Correct. Three arguments map to three parameters in order.
-
Match each parameter to its type
- string make
- Text
- int year
- Whole number
- decimal price
- Decimal number
- bool active
- True/false
Next lesson: Constructor overloading