Visual C # 2005 Quick Start writing method

Source: Internet
Author: User
Tags definition continue execution modify readline stub variable visual studio
Visual| QuickStart in the following exercise, you will create an application that includes a method that calculates the amount of a consultant's charges-assuming that the consultant charges a fixed fee each day, depending on how many days of work they will charge. First you develop the application's logic, and then use the Generate Method Stub wizard to write the method used by this logic. Next, we'll run the method in a console application to get the final impression of the program. Finally, we will use the visual Studio 2005 debugger to check the method invocation.

   Developing application logic

1. In Visual Studio 2005, open the \microsoft press\visual CSharp Step under the My Documents folder by Step\chapter 3\ The dailyrate item in the Dailyrate subfolder.

2. In Solution Explorer, double-click the Program.cs file to display the program in the Code and Text Editor window.

3. Add 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 you just added in the Run method calls the Readdouble method (which is about to begin writing this method) so that the user can enter the consultant's daily rate. The next statement calls the Readint method (which we write immediately) to get the number of days. Finally, the Writefee method (waiting to be written) is called 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 obtains the day rate and the number of days, and calculates the total amount to be paid.

Note that because the Readdouble,readint,writefee or Calculatefee methods have not yet been written, IntelliSense cannot automatically list them when you enter the above code. In addition, do not attempt to build the program, because it is sure to fail.

   to write a method using the Generate Method Stub wizard

1. In the Code and Text Editor window, click the Readdouble method call in the Run method.

A small underline icon is then displayed below the first letter ("R") of the readdouble. Moving the mouse pointer to the letter "R" automatically appears with an icon. Hovering over this icon displays a ToolTip: the option to generate the method stub (Shift + Alt + F10), and provides a drop-down menu. When you click the Drop-down menu, you see an option: Generate a method stub for "readdouble" in "Dailyrate.program".

2. Click the Readdouble method stub option in Generate Dailyrate.program.

The Build Method Stub wizard then examines the call to the Readdouble method, determines the parameter type and return value, and generates a method with the default implementation, as follows:

Private double readdouble (string p)
{
throw new Exception ("the method or operation isn't implemented.");
}
The new method is created using a private qualifier. The method body currently only throws an exception. We will replace the principal with our own statement in the next step.

3. Remove throw new Exception (...) from the Readdouble method. ; statement, replace it with the following line of code:

Console.Write (P);
String line = Console.ReadLine ();
Return double. Parse (line);
The above code block prints the string in the variable p to the screen. The variable is the string parameter that the calling method is passed, which contains a message that prompts the user to enter a daily rate. The user enters a value that is read in a string by the ReadLine method, and is passed double. The Parse method converts to a double value. The result is passed back as the return value of the method call.

Note The ReadLine method is a method that is associated with WriteLine, which reads the user's input from the keyboard until the ENTER key is pressed. The text entered by the user is returned as the return value.

4. In the Run method, click the Readint method call to generate a method stub for the Readint method, as in the previous procedure.

The Readint method is generated using a default implementation.

Tip To generate a method stub, you can also right-click a method call and choose Generate method Stub from the pop-up menu.

5. Replace the body of the Readint method with the following statement:

Console.Write (P);
String line = Console.ReadLine ();
return int. Parse (line);
This code block is very similar to the Readdouble method. The only difference is that the method returns an int value, so you want to use Int. The Parse method converts a string into an integer.

6. Right-click the Calculatefee method call in the Run method and select Generate method stub.

The Calculatefee method is then generated:

Private Object Calculatefee (double dailyrate, int noofdays)
{
throw new Exception ("The method or operation are not implemented");
}
Note that the Generate Method Stub wizard uses the Passed-in argument name to create an afterlife parameter name (of course, you can change the parameter name if it doesn't feel right). More interesting is the return type of the method, which is currently object. This indicates that the Build Method Stub wizard cannot determine what type of value the method should return based on the current context. The object type simply means the same thing, and you should modify it to the type you want when adding specific code to the method.

7. Modify the definition of the Calculatefee method so that it returns a double value:

Private double Calculatefee (double dailyrate, int noofdays)
{
throw new Exception ("The method or operation are not implemented");
}
8. Replace the body of the Calculatefee method with the following statement, which calculates the product of the two parameter values to obtain the amount that needs 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 stub.

The Writefee method is then generated. Note that the Build Method stub wizard determines that the parameter of the Writefee method should be a double parameter, based on the definition of the Calculatefee method. Also, the method call does not use a return value, so the method's type is void:

private void Writefee (double p)
{
...
}
10. Enter 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, and when evaluated, it is replaced by the value of the expression after the string (p * 1.1).

11. Select "Generate" | Build the solution.

Tip If you are fully familiar with the syntax, you can also write the method by typing it directly into the Code and Text Editor window. It is not always important to use the Generate Method stub option.

   Refactoring Code

One of the most useful features of Visual Studio 2005 is refactoring your code. At some point, we need to write the same (or very similar) code in multiple locations in the application. In this case, you can select the code block you just entered and choose Refactor | from the menu bar. Extraction method ". The Extract Method dialog box appears, prompting you to enter the name of a new method that will be used to contain the code you just entered. Please enter a method name and click OK. The system then creates the method and shifts the code you just entered into it, and the code you just entered is replaced by a call to the method. The Extract method also has some intelligence to determine whether the method should get any parameters and return values.

   Test Program

1. Select "Debug" | " Start execution (without debugging), Visual Studio 2005 will build the program and run it. A console window is displayed at run time.

2. After entering Your daily Rate (enter the day rate) prompt, enter 525, and then press ENTER.

3. After you enter the number of days (enter the day) prompt, enter 17, and then press ENTER.

The program displays the following message on the console:

The consultant ' s fee is:9817.5

Press ENTER 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 will see the moment each method is invoked (this action is called a jump) and see how each return statement returns control to the caller (this action is called a jump). When you enter and leave methods, you need to use the tools on the Debug toolbar. However, when you run an application in debug mode, the same command can also be selected from the Debug menu.

   To execute each method sequentially using the Visual Studio 2005 Debugger

1. In the Code and Text Editor window, locate the Run method.

2. Align the mouse pointer with 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 row and choose "Run to Cursor" from the pop-up menu.

The program starts running and pauses after the first statement of the Run method is reached. 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, make sure the Debug toolbar has been checked. The Debug toolbar might dock next to another toolbar. If you can't find this toolbar, try hiding it temporarily using the Toolbars command on the View menu, and notice which buttons disappear from the interface. When you display the toolbar again, you know where it should appear.

Tip To separate the Debug toolbar, use the handle to the left of the toolbar and drag it over the Code and Text Editor window.

5. Click the Step by Step button on the Debug toolbar. This action causes the debugger to jump into the method that is being invoked. The yellow arrow on the left points to the starting brace of the Readdouble method. Click the Step by Step button again, and the pointer will move to the first statement: Console.Write (P);

Tip Pressing the F11 key is equivalent to clicking the Step by Step button on the Debug toolbar.

6. Click the Process-by button on the Debug toolbar. This causes the method to execute the next statement without debugging it. The yellow arrow points to the second statement of the method, which displays the "Enter Your daily Rate" hint in a console window (the console window may be hidden behind Visual Studio 2005).

Tip Pressing the F10 key is equivalent to clicking the process-by button on the Debug toolbar.

7. Click the Process-by button on the Debug toolbar. This time, the yellow arrow disappears and the console window gets the focus because the program is executing the Console.ReadLine method, requiring the user to enter some content.

8. Enter 525 in the console window and press ENTER to continue.

Control will then return to Visual Studio 2005. The yellow arrow will appear in the third line of the method.

9. Do not make any click action, move the mouse pointer over the reference to the line variable in the second or third row of the method (specifically, which row does not matter).

A ScreenTip appears, showing the current value of the line variable (525). With this feature, you can determine that the variable is already set to a value of its own expectation when the method is executed.

10. Click the Jump button on the Debug toolbar.

This causes the current method to continue to run non-disruptively until the end. When the Readdouble method finishes executing, the yellow arrow refers back to the first statement of the Run method.

Tip pressing SHIFT + F11 key is equivalent to clicking the Jump button on the Debug toolbar.

11. Click the Step by Step 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 button on the Debug toolbar.

This time, you chose to run the method directly without debugging the method on a per-statement basis. The console window will appear again, prompting for a number of days.

13. Enter 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 Step by Step button on the Debug toolbar.

The yellow arrow jumps to the beginning brace of the Calculatefee method. The method is invoked 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 Step by Step button on the Debug toolbar.

This time, the yellow arrow jumps to the beginning brace at the Writefee method.

17. Let the mouse pointer align the p variable in the definition of the method.

The value of P (8925.0) is then displayed.

18. Click the Jump button on the Debug toolbar.

The message "The consultant ' fee is: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 to display). The yellow Arrow returns the third statement of the Run method.

19. Click the Continue button on the Debug toolbar to make the program run continuously instead of pausing at each statement.

The application will always run to the end.

Tip You can also press the F5 key to continue execution in the debugger.

Congratulations! You have successfully written and invoked the methods and debugged them with the visual Studio 2005 debugger.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.