Exercise: Methods and Conditions

Write 15 methods for three small businesses, using parameters, return values, ref and out, and conditions, and check each one with tests.

Apprentice · C# · Updated

By

Three small businesses need your help: a backyard basketball league, Claire's cookie shop, and Elliot's lawn-care business. Each needs a few calculations, and each calculation is a method for you to write. Tests check every method as you go.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-methods-and-conditions, also linked from the Exercise box beside the lesson. Clone it into your bootcamp folder. In Git Bash:

cd ~/bootcamp
git clone https://github.com/ask-codey/exercise-methods-and-conditions.git

Git makes a folder, exercise-methods-and-conditions, with the exercise code inside.

The folder holds two projects:

  • MethodsExercise: your code. Each business is a class of methods in its own file: BackyardBasketball.cs, ClairesCookies.cs and ElliotsYardCare.cs.
  • MethodsExercise.Tests: the tests that check your methods. You don't need to change these.

Open MethodsExercise.slnx in Visual Studio, or open the folder in VS Code.

What to do

Every method is already declared, with its parameters and return type, and returns 0 for now. The comment above it says what it should return, with examples:

/*
 * Return the percentage of games won, as a whole number.
 *
 * CalculateWinningPercentage(7, 3) -> 70
 * CalculateWinningPercentage(5, 5) -> 50
 */
public static int CalculateWinningPercentage(int gamesWon, int gamesLost)
{
    return 0;
}

Replace return 0; with your own code. The first line of each file, namespace MethodsExercise;, puts the file's class in the MethodsExercise namespace (Where a Variable Lives: Scope and Code Blocks); leave it as it is.

Keeping score: ref and out

The last two methods in BackyardBasketball.cs practice Passing Values to a Method: by Value and by Reference:

  • AddBasket(ref int teamScore, bool isThree) returns nothing. It adds 3 points to the caller's teamScore for a three-pointer (isThree is true), or 2 points for a two-pointer. With int score = 10;, AddBasket(ref score, true); leaves score at 13.
  • TryReadScore(string text, out int score) checks a score the scorekeeper typed. When text is a whole number from 0 to 200 (0 and 200 included), it returns true and hands the number back through score: TryReadScore("42", out int score) returns true with score at 42. For anything else, such as "forty", "-5" or "250", it returns false and hands back 0.

For now, AddBasket does nothing and TryReadScore returns false with a score of 0.

Check your work

In Visual Studio, choose Test > Run All Tests. Or, in Git Bash, from the folder with the .slnx file:

dotnet test

At first almost every test fails. Each method you finish turns its tests green. When a test fails, its message says which values it used and what it expected, for example A team with 5 wins and 10 losses has won 33% of its games.

You can also try a method in Program.cs and run the project with Ctrl+F5.

Hints

  • Work out an example by hand first. If you can't get 33 from 5 wins and 10 losses with a calculator, code won't help yet.
  • Integer division drops the fraction. 5 * 100 / 15 is 33. Multiply before you divide.
  • Math.Ceiling rounds up and Math.Round(value, 2) rounds to cents. You met both in Arithmetic and Expressions in C#.
  • Methods can call methods. CalculateProfit needs the cost, and CalculateCost already works it out.
  • Write your own helper. Three of Claire's methods add the same sales tax. A small method of your own, such as AddTax(decimal subtotal), keeps that rule in one place.
  • int.TryParse already has an out parameter. Pass your own out int score straight on to it, then check the range.
  • Pick the right decision. A true/false choice suits ?: or if; a list of exact names suits a switch; ranges suit if and else if.

When you're done

Every test is green. Read your code again, as if someone else wrote it: are the names clear? Is any calculation written twice? Tidy it up and run the tests again; they'll tell you if you broke anything.

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here.

  1. On GitHub, click +, then New repository. Name it (for example exercise-methods-and-conditions), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In a terminal in your exercise folder (Git Bash on Windows), send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-methods-and-conditions.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-methods-and-conditions, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

These are the same steps every real feature takes: a method with a clear name, the values it needs, a decision or two, and tests that prove it works.

Key terms

Related