94.7k views
4 votes
Using default arguments, write a function that asks the user for a number and returns that number. the function should accept a string prompt from the calling code. if the caller does not supply a string prompt, the function should use a generic prompt. next, using function overloading, write a function that achieves the same result.

User RobLabs
by
8.0k points

1 Answer

5 votes
Here's a solution in C#:

static int AskNumber(string prompt = "Please enter a number: ") { int number; bool numberOK = false;
do { Console.WriteLine(prompt); var numberString = Console.ReadLine(); numberOK = int.TryParse(numberString, out number); } while (!numberOK);
return number;
}

If you want to replace the default argument approach with function overloading, you change the function heading to:

static int AskNumber(string prompt ) {
// rest stays the same
}

And add this overload:

static int AskNumber() { return AskNumber("Please enter a number"); }

The compiler will figure out which one to call, so both these will work:

static void Main(string[] args) { AskNumber("Input some digits"); AskNumber(); }
User Omar Awamry
by
8.2k points