C # Writing method

Source: Internet
Author: User

In the following exercise, you will create an application that contains a method that calculates the charge amount for a consultant-assuming that the consultant charges a fixed fee every day, depending on how many days it is working. Start by developing the logic of your application, and then use the Generate Method Stub wizard to write out 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'll use the visual Studio 2005 debugger to check for method calls.

Developing application logic

1. In Visual Studio 2005, open the \microsoft press\visual CSharp Step by Step\chapter 3\ in the My Documents folder 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 body of the Run method:

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 block of code that you just added in the Run method calls the Readdouble method (which starts writing this method right away) so that the user can enter the advisor's daily rate. The next statement calls the Readint method (also written by us 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 gets the daily rate and the number of days, and calculates the total amount to be paid.

Note Because Readdouble,readint,writefee or Calculatefee methods are not yet written, IntelliSense cannot automatically list them when entering the above code. Also, do not attempt to build the program first, because it will definitely fail.

Use the Generate Method Stub wizard to write methods

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 the mouse pointer over the icon displays a tooltip: "Options for generating a method stub (Shift + Alt + F10)" and provides a drop-down menu. Click the drop-down menu and you'll see an option: Generate a method stub for "readdouble" in "Dailyrate.program".

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

The Generate 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 is not implemented.");
}

The new method is created with a private qualifier. The method body currently only throws an exception. We will replace the subject with our own statement in the next step.

3. Remove the 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 code block above will output the string from the variable p to the screen. The variable is a string parameter that is passed by the calling method, which contains a message prompting the user to enter a daily rate. The user enters a value that is read into a string by means of the ReadLine method and double. The parse method is converted 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 compatible with WriteLine, which reads the user from the keyboard until the input is pressed before the ENTER key. The text entered by the user is returned as a return value.

4. In the Run method, click the Readint method call, and in the same procedure as before, generate a method stub for the Readint method.

The Readint method is generated using a default implementation.

Tip in order 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 block of code is very similar to the Readdouble method. The only difference is that the method returns an int value, so 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 is not implemented");
}

Note that the Generate Method Stub wizard uses the passed-in argument name to create a form parameter name (and, of course, you can change the parameter name if you don't think it is appropriate). More interesting is the return type of the method, which is currently object. This indicates that the Generate Method Stub wizard cannot determine what type of value the method should return based on the current context. The object type simply means "something", and when you add specific code to the method, you should modify it to the type you want.

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 is not implemented");
}

8. Replace the body of the Calculatefee method with the following statement, which calculates the product of two parameter values to obtain 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 stub.

The Writefee method is then generated. Note that the Generate Method Stub wizard determines, based on the definition of the Calculatefee method, that the parameters of the Writefee method should be a double argument. In addition, the method call does not use a return value, so the method is of type 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 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 a method by typing it directly in 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 places in the application. In this case, you can select the code block you just entered, and then 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 will then create this method and transfer the code you just entered into it, and the code you just entered is replaced with 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 enter Your Daily rate (enter the daily rates) prompt, enter 525, and then press ENTER.

3. After entering the number of days prompt, enter 17 and 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 called (this action is called jumping in) and see how each return statement returns control to the caller (this action is called jumping out). When you enter and leave a method, you need to use the tools on the Debug toolbar. However, when you run the application in debug mode, the same commands can also be selected from the Debug menu.

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 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 row and select Run to cursor from the pop-up menu.

The program starts running and pauses after the first statement of the Run method arrives. A yellow arrow on the left side 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 is checked. The debug toolbar may be docked next to other toolbars. If you can't find the toolbar, try hiding it temporarily using the Toolbars command on the View menu, and notice which buttons disappear from the interface. Re-display the toolbar to see where it should appear.

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

5. Click the Step Over button on the Debug toolbar. This action causes the debugger to jump into the method being called. The yellow arrow on the left points to the starting brace for the Readdouble method. When you click the Step by Step button again, the pointer shifts to the first statement: Console.Write (P);

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

6. Click the Step Over 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, and the program displays the "Enter Your Daily rate" Prompt in a console window (the console window may be hidden behind Visual Studio 2005).

Tip Pressing the F10 key is equivalent to clicking the Step Over button on the Debug toolbar.

7. Click the Step Over 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 that requires the user to enter some content.

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

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

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

A ScreenTip appears, showing the current value of the line variable (525). Using this feature, you can determine that the variable has been set to its desired value at the time of execution of the method.

10. Click the "Jump Out" button on the "Debug" toolbar.

This causes the current method to continue to run without interruption until the end. When the Readdouble method finishes executing, the yellow arrow points back to the first statement of the Run method.

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

11. Click the Step Over button on the Debug toolbar.

A yellow arrow moves to the second statement of the Run method:

int noofdays = READINT ("Enter The number of Days:");

12. Click the Step Over button on the Debug toolbar.

This time, you chose to run the method directly without having to debug 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. A yellow arrow moves to the third statement of the Run method:

Writefee (Calculatefee (Dailyrate, noofdays));

14. Click the Step Over button on the Debug toolbar.

The yellow arrow jumps to the beginning brace of the Calculatefee method. The method is called before the Writefee method.

15. Click the "Jump Out" button on the "Debug" toolbar.

A yellow arrow jumps back to the third statement of the Run method.

16. Click the Step Over button on the Debug toolbar.

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

17. Align the mouse pointer to the P variable in the method definition.

The value of P (8925.0) is then displayed.

18. Click the "Jump Out" button on the "Debug" toolbar.

The message "The consultant's fee is:9817.5" is then displayed in the console window (if the console window is hidden after visual Studio 2005, bring it to the foreground to display). A 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 without pausing at each statement.

The application will run until the end.

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

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

C # Writing method

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.