Lesson Weekend

We've learned how objects can help us store and organize information. But the real power of objects is that they can also do things with that information. A method is essentially a function that is part of an object's blueprint.

In Intro, we learned about prototypes for JavaScript objects. C# has similar functionality but we don't use the term prototype to describe it. In C#, we call them methods or object methods.

Writing Custom Methods for Objects


When people are looking to buy a car, they usually begin with a budget.

Let's create a method we can call on Cars that returns whether they fit within a user's budget. It will take the maximum amount a customer is willing to spend and compare this amount to the specific price of a Car. If the vehicle costs less than the customer's budget, the method will return true. If not, it will return false:

Car.cs
...

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

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

...
  • We define a WorthBuying() method in the Car class. This method can only be called on Car objects because it's specifically defined in this class.

  • The access modifier public means this method is available to anyone. Once again, we'll get back to access modifiers more later).

  • We also declare that this method will return a bool type.

  • We state that WorthBuying() takes one argument: maxPrice. We declare this argument to be an int. maxPrice will represent the most money a customer at our car dealership is willing to spend.

  • We return the result of (Price <= maxPrice). Price refers to the Price attribute of the specific instance of Car this method is called on. This price is compared to the user-provided maxPrice. Our method will then return true or false depending on whether the user's maxPrice is greater or less than the cost of the vehicle.

Custom Methods in C# Applications


Let's add this method to our program. Since we'll need to gather budget information from the user, we'll need to add code to Main() to ask the user what their budget is:

Car.cs
...

public class Car
{
  ...
}

public class Program
{
  public static void Main()
  {
    ...

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

    //New code starts here
    Console.WriteLine("Enter maximum price: ");
    string stringMaxPrice = Console.ReadLine();
    int maxPrice = int.Parse(stringMaxPrice);
...

All user-provided input comes into our application as string type so stringMaxPrice is declared as a string. We then use the int.Parse() method to transform this string back into the int type, since that's what our WorthBuying()method expects as an argument.

Next, let's create a new List to hold cars that meet the user's budget requirements. This will be different from our list of all cars because not all cars will fit every user's budget. We'll define a new List called CarsMatchingSearch to gather the user's budget requirements:

Car.cs
...

public class Car
{
  ...
}

public class Program
{
  public static void Main()
  {
    ...

    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); //new code

    foreach(Car automobile in Cars)
    {
      ...
    }
...

Next, let's add another loop that calls the WorthBuying() method on all cars, adding only the cars meeting the user's budget requirements to the new CarsMatchingSearch List. We'll also modify our existing loop to only return cars that meet a user's budget.

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

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

//This foreach loop is new.
foreach (Car automobile in Cars)
{
  if (automobile.WorthBuying(maxPrice))
  {
    CarsMatchingSearch.Add(automobile);
  }
}

//This loop has been modified.
foreach(Car automobile in CarsMatchingSearch)
{
  Console.WriteLine(automobile.MakeModel);
}
...

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 bool WorthBuying(int maxPrice)
  {
    return (Price <= maxPrice);
  }
}

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;

    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);
    }
  }
}

If we compile and launch the application, our new WorthBuying() method successfully filters the list of displayed cars based on our user's budget.

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