c sharp writes method instances
- 2020-05-06 11:49:20
- OfStack
Develop the application logic
1. opens the DailyRate project in Visual Studio 2005 in the My Documents folder \Microsoft Press\Visual Step Step Step Chapter 3\DailyRate subfolder.
In solution explorer, double-click the Program.cs file to display the program in the code and text editor window.
3. adds the following statement to the run method body:
double dailyRate = readDouble("Enter your daily rate: ");
int noOfDays = readInt("Enter the number of days: ");
writeFee(calculateFee(dailyRate, noOfDays));
When the application starts, the run method is called by the Main method.
The code block that was just added to the run method invokes the readDouble method (which is about to start writing) to allow the user to enter the consultant's daily rate. The next statement calls the readInt method (also written by us in a moment) to get the days. Finally, the writeFee method is called (waiting to be written) to display the results on the screen. Note that the value passed to writeFee is the value returned by the calculateFee method (the last method to write), which takes the daily rate and number of days and calculates the total amount to be paid.
Note that has not yet written readDouble, readInt, writeFee, or calculateFee methods, so intellisense cannot automatically list them when entering the above code. Also, don't try to build the program yet, because it's bound to fail.
Use the generate method stub wizard to write the method
In the code and text editor window, click the readDouble method call in the run method.
A small underlined icon is then displayed below the first letter of readDouble ("r"). Move the mouse pointer to the letter "r" and an icon will appear automatically. Hovering over the icon displays a tooltip: "options for generating method stubs (Shift + Alt + F10)" with a drop-down menu. Click the drop-down menu and you will see an option to generate a method stub for "ReadDouble" in "DailyRate.Program".
2. click the option to generate "ReadDouble" method stubs in "DailyRate.Program".
The generate method stub wizard then checks the call to the readDouble method, determines the parameter types and return values, and generates a method with a default implementation, as shown below:
private double readDouble(string p)
{
throw new Exception("The method or operation is not implemented.");
}
The new method is created using an private qualifier. The method body is currently just throwing an exception. We will replace the body with our own statement in the next step.
3. delete throw new Exception(...) ; Statement, replace it with the following line of code:
Console.Write(p);
string line = Console.ReadLine();
return double.Parse(line);
The code block above prints the string in the variable p to the screen. This variable is the string argument that the calling method is passing, which contains a message that prompts the user for the daily rate. The user enters a value that will be read into a string by the ReadLine method and converted to an double value by the double.Parse method. The result is returned as the return value of the method call.
Note that the ReadLine method is a companion to WriteLine that reads the user's input from the keyboard until the enter key is pressed. The text entered by the user is returned as a return value.
In the run method, click the readInt method call, and follow the same procedure to generate a method stub for the readInt method.
The readInt method will be generated using a default implementation.
prompts to generate a method stub, you can also right-click a method call and select generate method stub from the pop-up menu.
5. replaces the body of the readInt method with the following statement:
Console.Write(p);
string line = Console.ReadLine();
return int.Parse(line);
The code block is very similar to the readDouble method. The only difference is that the method returns an int value, so use the int.Parse method to convert the string to an integer.
6. right - click the calculateFee method call in the run method and select generate method stubs.
The calculateFee method:
is then generated
private object calculateFee(double dailyRate, int noOfDays)
{
throw new Exception("The method or operation is not implemented");
}
Note that the generation method stub wizard USES the incoming argument name to generate the forming parameter name (although you can change the parameter name if you feel that it is inappropriate). More interesting is the method's return type, currently object. This indicates that the generate method stub wizard cannot determine what type of value a method should return based on the current context. The object type simply means "something," and when you add specific code to a method, you should change it to the type you want.
7. modifies the definition of the calculateFee method so that it returns an double value:
private double calculateFee (double dailyRate, int noOfDays)
{
throw new Exception("The method or operation is not implemented");
}
8. replaces the body of the calculateFee method with the following statement, which computes the product of two parameter values to get the amount to be paid and returns the result.
return dailyRate * noOfDays;
9. right - click the writeFee method call in the run method and select generate method stubs.
The writeFee method is then generated. Note that the generate method stub wizard determines from the definition of the calculateFee method that the writeFee method parameter should be an double parameter. In addition, the method call does not use a return value, so the method type is void:
private void writeFee(double p)
{
...
}
10. enters the following statement inside the writeFee method:
Console.WriteLine("The consultant's fee is: {0}", p * 1.1);
Note that this version of the WriteLine method demonstrates how to take advantage of a simple format string. {0} is a placeholder; When evaluated, it is replaced by the value of the expression following the string (p * 1.1).
11. select "build" | "build solution".
Refactor the code
One very useful feature of Visual Studio 2005 is refactoring of the code. Sometimes we need to write the same (or very similar) code in multiple locations in the application. In this case, you can select the block of code you just entered, and then select refactor | extract method from the menu bar. The extract method dialog box appears, prompting you to enter the name of a new method that will contain the code you just entered. Enter a method name and click ok. The system then creates the method and moves the code you just entered into it, which is replaced with a call to the method. The extract method also has the intelligence to determine whether the method should take any parameters and return values.
Test program
1. select debug | start execution (no debugging), Visual Studio 2005 will generate the program and run it. The runtime displays a console window.
After being prompted by Enter Your Daily Rate(enter daily rate), enter 525 and press enter.
After being prompted by Enter The Number Days(number of days), enter 17 and press enter.
The program displays the following message on the console:
The consultant's fee is: 9817.5
Press the enter key to return to the Visual Studio 2005 programming environment.
In the last exercise, you will use the Visual Studio 2005 debugger to run the program at a slower pace. You'll see when each method is called (the action is called a jump) and how each return statement returns control to the caller (the action is called a jump). When entering and leaving a method, you need to use the tools on the debug toolbar. However, when running the application in debug mode, the same command can be selected from the debug menu.
Execute each method
in turn using the Visual Studio 2005 debugger
In the code and text editor window, find the run method.
2. aligns the mouse pointer to the first statement in the run method.
The first statement of the run method is:
double dailyRate = readDouble("Enter your daily rate: ");
3. right - click anywhere in the line and select run to cursor from the pop-up menu.
The program starts running and pauses after reaching the first statement of the run method. A yellow arrow to the left of the code and text editor window indicates the current statement, which is also highlighted with a yellow background.
4. select "view" | "toolbar" and make sure the "debug" toolbar is checked. The debug toolbar may dock next to other toolbars. If you can't find the toolbar, try hiding it temporarily with the toolbar command in the view menu and notice which buttons are missing from the screen. Redisplay the toolbar to see where it should appear.
Prompt to separate the debug toolbar, use the control point on the left of the toolbar and drag and drop it above the code and text editor window.
5. click the statement by statement button on the debug toolbar. This action causes the debugger to jump into the method being invoked. The yellow arrow on the left will point to the opening brace of the readDouble method. Click the statement by statement button again, and the pointer goes to the first statement: Console.Write (p);
Prompting to press F11 is equivalent to clicking the statement by statement button on the debug toolbar.
6. click the process by process button on the debug toolbar. This causes the method to execute the next statement without debugging it. The yellow arrow will point to the second statement of the method, and the program will prompt "Enter Your Daily Rate" in a console window (the console window may be hidden behind Visual Studio 2005).
Prompting to press F10 is equivalent to clicking the progress button on the debug toolbar.
7. click the process by process button on the debug toolbar. This time, the yellow arrow disappears and the console window gains focus because the program is executing the Console.ReadLine method, which asks the user to enter something.
8. enter 525 in the console window and press enter to continue.
The control then returns Visual Studio 2005. The yellow arrow will appear in the third line of the method.
9. does not make any clicks, move the mouse pointer over the reference to the line variable in the second or third line of the method (it does not matter which line is aligned).
A screen prompt appears that shows the current value of the line variable (525). Using this feature, you can be sure that a variable has been set to a value that you expect at the time of method execution.
10. click the jump button on the debug toolbar.
This causes the current method to continue running without interruption until the end. When the readDouble method is finished, the yellow arrow points back to the first statement of the run method.
Pressing Shift + F11 is equivalent to clicking the "out" button on the debug toolbar.
11. click the statement by statement button on the debug toolbar.
The yellow arrow moves to the second statement of the run method:
int noOfDays = readInt("Enter the number of days: ");
12. click the process by process button on the debug toolbar.
This time, you chose to run the method directly instead of debugging it statement by statement. The console window will appear again, prompting for a day.
13. type 17 in the console window and press enter to continue.
Control will return to Visual Studio 2005. The yellow arrow moves to the third statement of the run method:
writeFee(calculateFee(dailyRate, noOfDays));
14. click the statement by statement button on the debug toolbar.
The yellow arrow jumps to the opening brace of the calculateFee method. This method will be called before the writeFee method.
15. click the jump button on the debug toolbar.
The yellow arrow jumps back to the third statement of the run method.
16. click the statement by statement button on the debug toolbar.
This time, the yellow arrow jumps to the opening brace of the writeFee method.
17. aligns the mouse pointer to the p variable in the method definition.
The value of p (8925.0) is then displayed.
18. click the jump button on the debug toolbar.
The message "The consultant s fee 9817.5" is then displayed in the console window (if the console window is hidden after Visual Studio 2005, please bring it to the foreground for display). The yellow arrow returns the third statement of the run method.
19. clicks the continue button on the debug toolbar to make the program run continuously without pausing at each statement.
The application will run until the end.
prompts to press F5 to continue execution in the debugger.
A: congratulations! You have successfully written and called the methods and debugged them using the Visual Studio 2005 debugger.