In the following exercises, you'll create an application method that calculates how much a consultant would charge for a given number of consultancy days at a fixed daily rate. You will start by developing the logic for the application and then use the Generate Method Stub Wizard to help you write the methods that are used by this logic. Next, you'll run these methods in a console application to get a feel for the program. Finally, you'll use the Visual Studio 2005 debugger to step in and out of the method calls as they run.
Using Visual Studio 2005, open the DailyRate project in the \Microsoft Press\Visual CSharp Step by Step\Chapter 3\DailyRate folder in your My Documents folder.
In the Solution Explorer, double-click the file Program.cs to display the program in the Code and Text Editor window.
Add the following statements to the body of the run method:
double dailyRate = readDouble("Enter your daily rate: "); int noOfDays = readInt("Enter the number of days: "); writeFee(calculateFee(dailyRate, noOfDays));
The run method is called by the Main method when the application starts (the way in which it is called requires an understanding of classes, which we will look at in Chapter 7, “Creating and Managing Classes and Objects”) .
The block of code you have just added to the run method calls the readDouble method (which you will write shortly) to ask the user for the daily rate for the consultant. The next statement calls the readInt method (which you will also write) to obtain the number of days. Finally, the writeFee method (to be written) is called to display the results on the screen. Notice that the value passed to writeFee is the value returned by the calculateFee method (the last one you will need to write), which takes the daily rate and the number of days and calculates the total fee payable.
In the Code and Text Editor window, click the readDouble method call in the run method.
A small underscore character appears underneath the first letter ("r") of readDouble. If you move the cursor over the letter "r", an icon appears. If you hover the mouse over this icon,the tooltip "Options to generate a method stub (Shift + Alt + F10)" appears, with a drop-down menu. Click the drop-down menu, and the option “Generate method stub for 'readDouble' in 'DailyRate.Program'” apppears, as shown here:
Click Generate method stub for 'readDouble' in 'DailyRate.Program'.
The Generate Method Stub Wizard examines the call to the readDouble method, ascertains the type of its parameters and return value, and generates a method with a default implementation, like this:
private double readDouble(string p)
{
throw new Exception("The method or operation is not implemented.");
}
The new method is created with the private qualifier, which will be described in Chapter 7. The body of the method currently just throws an Exception. (Exceptions will be described in Chapter 6.) You will replace the body with your own code in the next step.
Delete the throw new Exception(…); statement from the readDouble method, and replace it with the following lines of code:
Console.Write(p); string line = Console.ReadLine(); return double.Parse(line);
This block of code outputs the string in variable p to the screen. This variable is the string parameter passed in when the method is called, and contains a message prompting the user to type in their daily rate. The user types in a value, which is read into a string by using the ReadLine method and converted into a double by using the double.Parse method. The result is passed back as the return value of the method call.
Click the call to the readInt method in the run method, and use the same process as before to generate a method stub for the readInt method.
The readInt method is generated with a default implementation.
Replace the body of the readInt method with the following statements:
Console.Write(p); string line = Console.ReadLine(); return int.Parse(line);
This block of code is very similar to the readDouble method. The only difference is that the method returns an int value, so the string is converted into a number by using the int.Parse method.
Right-click the call to the calculateFee method in the run method, and then click Generate Method Stub.
The calculateFee method is generated:
private object calculateFee(double dailyRate, int noOfDays) { throw new Exception("The method or operation is not implemented"); }
Notice that the Generate Method Stub Wizard uses the name of the arguments passed in to generate names for the parameters. (You can of course change the parameter names if they are not suitable.) What is more intriguing is the type returned by the method, which is object. The Generate Method Stub Wizard is unable to determine exactly what type of value should be returned by the method from the context in which it is called. The object type just means a “thing,” and you should change it to the type you require when you add the code to the method. The object type will be described in more detail in Chapter 7.
Change the definition of the calculateFee method so that it returns a double:
private double calculateFee double dailyRate, int noOfDays) { throw new Exception("The method or operation is not implemented"); }
Replace the body of the calculateFee method with the following statement, which calulates the fee payable by multiplying the two parameters together and then returns it:
return dailyRate * noOfDays;
Right-click the call to the writeFee method in the run method, then click Generate Method Stub.
The writeFee method is generated. Note that the Generate Method Stub Wizard uses the definition of the calculateFee method to work out that its parameter should be a double. Also, the method call does not use a return value, so the type of the method is void:
private void writeFee(double p) { ... }
Type the following statements inside the writeFee method:
Console.WriteLine("The consultant's fee is: {0}", p * 1.1);
On the Build menu, click Build Solution.
On the Debug menu, click Start Without Debugging.
Visual Studio 2005 builds the program and then runs it. A console window appears.
At the Enter Your Daily Rate prompt, type 525, and then press Enter.
At the Enter The Number Of Days prompt, type 17, and then press Enter.
The program writes the following message to the console window:
The consultant's fee is: 9817.5
Press the Enter key to return control to the Visual Studio 2005 programming environment.
In the final exercise, you'll use the Visual Studio 2005 debugger to run your program in slow motion. You'll see when each method is called (this action is referred to as stepping into the method) and then see how each return statement transfers control back to the caller (also known as stepping out of the method). While you are stepping in and out of methods, you'll use the tools on the Debug toolbar. However, the same commands are also available on the Debug menu when an application is running in Debug mode.
In the Code and Text Editor window, find the run method.
Move the mouse pointer to the first statement in the run method.
The first statement in the run method is as follows:
double dailyRate = readDouble("Enter your daily rate: ");
Right-click anywhere on this line, and on the context menu, click Run To Cursor.
The program runs until it reaches the first statement in the run method, and then it pauses. A yellow arrow in the left margin of the Code and Text Editor window indicates the current statement, which is also highlighted with a yellow background.
On the View menu, point to Toolbars, and then make sure the Debug toolbar is checked.
If it was not already visible, the Debug toolbar opens. It might appear docked with the other toolbars. If you cannot see the toolbar, try using the Toolbars command on the View menu to hide it, and notice which buttons disappear. Then display the toolbar again. The Debug toolbar looks like this:
On the Debug toolbar, click Step Into.
This action causes the debugger to step into the method being called. The yellow cursor jumps to the opening curly brace at the start of the readDouble method. Click Step Into again. The cursor advances to the first statement:
Console.Write(p);
On the Debug toolbar, click Step Over.
This action causes the method to execute the next statement without debugging it (stepping into it). The yellow cursor moves to the second statement of the method, and the program displays the Enter Your Daily Rate prompt in a Console window before returning to Visual Studio 2005 (the Console window may be hidden behind Visual Studio).
On the Debug toolbar, click Step Over.
This time the yellow cursor disappears and the Console window gets the focus because the program is executing the Console.ReadLine method and is waiting for you to type something in.
Type 525 in the Console window, and then press Enter.
Control returns to Visual Studio 2005. The yellow cursor appears on the third line of the method.
Without clicking, move the mouse over the reference to the line variable on either the second or the third line of the method (it doesn't matter which).
A ScreenTip appears, displaying the current value of the line variable (“525”). You can use this feature to make sure that a variable has been set to an expected value while stepping through methods.
On the Debug toolbar, click Step Out.
This action causes the current method to continue running uninterrupted to its end. The readDouble method finishes, and the yellow cursor is placed back at the first statement of the run method.
On the Debug toolbar, click Step Into.
The yellow cursor moves to the second statement in the run method:
int noOfDays = readInt("Enter the number of days: ");
On the Debug toolbar, click Step Over.
This time you have chosen to run the method without stepping through it. The Console window appears again prompting you for the number of days.
In the Console window, type 17, and then press Enter.
Control returns to Visual Studio 2005. The yellow cursor moves to the third statement of the run method:
writeFee(calculateFee(dailyRate, noOfDays));
On the Debug toolbar, click Step Into.
The yellow cursor jumps to the opening curly brace at the start of the calculateFee method. This method is called first, before writeFee.
On the Debug toolbar, click Step Out.
The yellow cursor jumps back to the third statement of the run method.
On the Debug toolbar, click Step Into.
This time, the yellow cursor jumps to the opening curly brace at the start of the writeFee method.
Place the mouse over the p variable in the method definition.
The value of p, 8925.0, is displayed.
On the Debug toolbar, click Step Out.
The message The consultant's fee is: 9817.5 is displayed in the Console window. (You might need to bring the Console window to the foreground to display it if it is hidden behind Visual Studio 2005). The yellow cursor returns to the third statement in the run method.
On the Debug toolbar, click Continue to cause the program to continue running without stopping at each statement.
The application finishes running.
Congratulations! You've successfully written and called methods and used the Visual Studio 2005 debugger to step in and out of methods as they run.
If you want to continue to the next chapter
Keep Visual Studio 2005 running, and turn to Chapter 4.
If you want to exit Visual Studio 2005 now
On the File menu, click Exit. If you see a Save dialog box, click Yes to save your work.