Skip to main content

Functions using Functions

Functions can call another function! We also have already been doing this before:

Example 1. Functions using Functions​

Going back to GetPositiveDouble(), notice that it calls Console.ReadLine() inside another function (function-ception)

static double GetPositiveDouble()
{
double num = double.Parse(Console.ReadLine());
// ... other stuff ...
}

Example 2. Calculate Pay​

We can use GetPositiveDouble() instead of nesting loops ❤️

static double GetPayment(int shiftsWorked)
{
const double Wage = 16.75;
double totalHours = 0;
Console.WriteLine($"Lets see how much you worked these last {shiftsWorked} shifts...");
for (int i = 1; i <= shiftsWorked; i++)
{
totalHours += GetPositiveDouble();
}

return Wage * totalHours;
}

Example 3. Calculate Pay​

And now we can figure out the users pay! We can use GetPositiveDouble() instead of repeating logic ❤️

Console.WriteLine("How many shifts did you work?");
int shifts = (int) GetPositiveDouble(); // cast it from double -> int
double pay = GetPayment(shifts);
Console.WriteLine($"You made ${pay} (W O W)");

Because the validation lives in one place, improving GetPositiveDouble later improves every part of the program that uses it! So fun!