I’m obviously a newbie when it comes to C# and the following program is from a Charles Petzold book that I don’t fully understand. The parameter in the GetDouble method is a string named prompt. Nowhere is this declared and I think that’s what’s messing me up. I see that the Main method is calling GetDouble and is printing three strings to the console, but this whole thing looks weird to me. Is this typical programming design, or is this not industry standard, but for purposes of showing how things can be done? The book doesn’t give an answer either way. My fledgling programming self wouldn’t pass a string to the Main method. Can someone help straighten me out?
using System;
class InputDoubles
{
static void Main()
{
double dbase = GetDouble("Enter the base: ");
double exp = GetDouble("enter the exponent: ");
Console.WriteLine("{0} to the power of {1} is {2}", dbase, exp, Math.Pow(dbase, exp));
}
static double GetDouble(string prompt)
{
double value = Double.NaN;
do
{
Console.Write(prompt);
try
{
value = Double.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine();
Console.WriteLine("you enter an invalid number!");
Console.WriteLine("please try again");
Console.WriteLine();
}
}
while (Double.IsNaN(value));
return value;
}
}
Wait, it’s declared right there – in the header of the method:
promptis different from other variables that you have seen in that it is not a normal variable: it is a formal parameter of a method.Unlike regular variables which you initialize and assign explicitly with the assignment operator
=, formal parameters are assigned implicitly by virtue of calling a method. When you call the method, you pass it an expression with the actual parameter, which acts as an assignment of that expression to the formal parameter. Imagine that thepromptvariable is assigned"Enter the base: "before the first call, and then it is assigned"enter the exponent: "before the second call to understand what is going on when you callGetDouble.