Lesson Weekend

Now that we can create both classes and custom methods, let's explore a special type of method called a constructor. We can use constructors to DRY up our code and make the process of instantiating new objects much quicker.

Constructors


A constructor is a method that is called when a new instance of a class is created. Any information regarding the initial setup of a new object can be included in a constructor.

Writing Constructor Methods

Let's walk through adding a constructor to our Car class together:

Car.cs
...

public class Car
{
  public string MakeModel;
  public int Price;
  public int Miles;

  //New constructor code below.
  public Car(string makeModel, int price, int miles)
  {
    MakeModel = makeModel;
    Price = price;
    Miles = miles;
  }

  public bool WorthBuying(int maxPrice)
  {
    return (Price <= maxPrice);
  }
}

...

Constructors look a lot like other methods. Our constructor can take multiple parameters and also has an access modifier that we've set to public. Each of these parameters correspond to the fields a Car object should have, including an int value to represent its price, a string containing a Car object's make, and so on.

When we call our constructor, we will pass in arguments for a Car's MakeModel, Price, and Miles. A Car will be instantiated with the fields set to the arguments we've passed in. Note that the object's fields are in PascalCase while the constructor method's parameters are lowerCamelCase.

Our constructor method will also return an object of the class type it belongs to - in this case, our constructor will return an instance of Car.

Calling Constructor Methods

Constructors create new instances of a class when the new keyword is used. new denotes that we're creating a new instance of this class:

Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
  • Just like every other variable, it needs a type declaration. That's why the name of our custom class is the first element in this line of code.

  • It also has a name like any other variable. We're calling ours firstCar.

  • The word Car is included again after the new keyword because this is also the name of our constructor. It's best practice to name the constructor after the class it's called on.

  • Finally, we include the three arguments required by our constructor. They denote the make/model, price, and mileage of this car.

When our dealership gets another Car to sell, we can create another instance of this class, with different details:

Car secondCar = new Car("1981 Ford Pinto", 200, 36000);

Using Constructors in C# Applications

Let's use our new constructor in the command line interface of our car dealership application.

We can refactor this area of our program:

Car.cs
...

public class Program
{
  public static void Main()
  {
    Car volkswagen = new Car();
    volkswagen.MakeModel = "1974 Volkswagen Thing";
    volkswagen.Price = 1100;
    volkswagen.Miles = 368792;

    Car yugo = new Car();
    yugo.MakeModel = "1980 Yugo Koral";
    yugo.Price = 700;
    yugo.Miles = 56000;

    Car ford = new Car();
    ford.MakeModel = "1988 Ford Country Squire";
    ford.Price = 1400;
    ford.Miles = 239001;

    Car amc = new Car();
    amc.MakeModel = "1976 AMC Pacer";
    amc.Price = 400;
    amc.Miles = 198000;

  ...
...

We will use our new constructor instead:

Car.cs
...

public class Program
{
  public static void Main()
  {
    Car volkswagen = new Car("1974 Volkswagen Thing", 1100, 368792);
    Car yugo = new Car("1980 Yugo Koral", 700, 56000);
    Car ford = new Car("1988 Ford Country Squire", 1400, 239001);
    Car amc = new Car("1976 AMC Pacer", 400, 198000);
  ...
...

The entire updated file should look like this:

Car.cs
using System;
using System.Collections.Generic;

public class Car
{
  public string MakeModel;
  public int Price;
  public int Miles;

  public Car(string makeModel, int price, int miles)
  {
    MakeModel = makeModel;
    Price = price;
    Miles = miles;
  }

  public bool WorthBuying(int maxPrice)
  {
    return (Price <= maxPrice);
  }
}

public class Program
{
  public static void Main()
  {
    Car volkswagen = new Car("1974 Volkswagen Thing", 1100, 368792);
    Car yugo = new Car("1980 Yugo Koral", 700, 56000);
    Car ford = new Car("1988 Ford Country Squire", 1400, 239001);
    Car amc = new Car("1976 AMC Pacer", 400, 198000);

    List<Car> Cars = new List<Car>() { volkswagen, yugo, ford, amc };

    Console.WriteLine("Enter maximum price: ");
    string stringMaxPrice = Console.ReadLine();
    int maxPrice = int.Parse(stringMaxPrice);

    List<Car> CarsMatchingSearch = new List<Car>(0);

    foreach (Car automobile in Cars)
    {
      if (automobile.WorthBuying(maxPrice))
      {
        CarsMatchingSearch.Add(automobile);
      }
    }

    foreach(Car automobile in CarsMatchingSearch)
    {
      Console.WriteLine(automobile.MakeModel);
    }
  }
}

Constructors allow us to write cleaner and DRYer code. Moving forward, use constructor methods to create instances of custom classes in all your applications.

Terminology:


Constructor: A method called when a new instance of a class is created. Here's an example:

Examples

public Car(string makeModel, int price, int miles)
{
  MakeModel = makeModel;
  Price = price;
  Miles = miles;
}

The method name is capitalized. The object's fields are also capitalized while the constructor method's parameters are lowerCamelCase.

Constructors are called whenever we use the new keyword. For example: Car firstCar = new Car("1980 Yugo Koral", 700, 56000);.

Lesson 3 of 10
Last updated more than 3 months ago.