
10266A_03.ppt
- Количество слайдов: 19
Module 3 Declaring and Calling Methods
Module Overview • Defining and Invoking Methods • Specifying Optional Parameters and Output Parameters
Lesson 1: Defining and Invoking Methods • What Is a Method? • Creating a Method • Calling a Method • Creating and Calling Overloaded Methods • Using Parameter Arrays • Refactoring Code into a Method • Testing a Method • Demonstration: Refactoring and Testing a Method
What Is a Method? A method is a class member that contains a code block that represents an action: • All code belongs to a method • A C# application must have at least one method • Methods can be defined for private use by a type, or for public use by other types The Main method defines the starting point for an application C# supports instance and static methods Instance method int count = 99; string str. Count = count. To. String(); Static method string str. Count = “ 99”; count = Convert. To. Int 32(str. Count);
Creating a Method A method contains: • The method specification (access, return type, and signature) • The method body (code) Method signature: 1 Name (Pascal case) 2 Parameters (camel case) Each method signature must be unique in a type Example bool Lock. Report(string user. Name) { bool success = false; // Perform some processing here. return success; }
Calling a Method To call a method: • Specify the method name • Provide an argument for each parameter • Handle the return value Example method bool Lock. Report(string report. Name, string user. Name) {. . . ; } Method call bool is. Report. Locked = Lock. Report("Medical Report", “Don Hall"); Note: Arguments are evaluated in left-to-right order
Creating and Calling Overloaded Methods An overloaded method: • Has the same name as an existing method • Should perform the same operation as the existing method • Uses different parameters to perform the operation The compiler invokes the version that is appropriate to the arguments that are specified when the method is called Example void Deposit(decimal amount) { _balance += amount; } void Deposit(int dollars, int cents) { _balance += dollars + (cents / 100. 0 m); } The signature of the Deposit method is different for each implementation
Using Parameter Arrays Overloading may not be possible or appropriate if a method can take a variable number of arguments Example int Add(params int[] data) { int sum = 0; for (int i = 0; i < data. Length; i++) { sum += data[i]; } return sum; } Method call int sum = Add(99, 2, 55, -26);
Refactoring Code into a Method 1 Select the code that you want to extract to a method, right-click, point to Refactor, and then click Extract Method 2 In the Extract Method dialog box, in the New method name box, type a name for the method, and then click OK Example of refactored output Log. Message(message. Contents, file. Path); . . . private void Log. Message(string message. Contents, string file. Path) {. . . }
Testing a Method int Calculate(int operand. One, int operand. Two) { int result = 0; // Perform some calculation. return result; } Create Unit Test Wizard [Test. Method()] public void Calculate. Test() { Program target = new Program(); int operand. One = 0; int operand. Two = 0; int expected = 0; int actual; actual = target. Calculate(operand. One, operand. Two); Assert. Are. Equal(expected, actual); . . . }
Demonstration: Refactoring and Testing a Method In this demonstration, you will do the following: • Open the existing application and view the existing code • Refactor an existing code block • Generate a unit test for the Generate. Random. Numbers method • Examine the auto-generated unit test method • Modify the auto-generated unit test method • Run the unit test
Lesson 2: Specifying Optional Parameters and Output Parameters • What Are Optional Parameters? • Calling a Method by Using Named Arguments • What Are Output Parameters?
What Are Optional Parameters? Optional parameters enable you to define a method and provide default values for the parameters in the parameter list: • They are useful for interoperating with other technologies that support optional parameters • They can provide an alternative implementation where overloading is not appropriate Example void My. Method( int. Data, float. Data second, int more. Int. Data = 99) {. . . } // Arguments provided for all three parameters My. Method(1 o, 123. 45, 99); // Arguments provided for 1 st two parameters only My. Method(100, 54. 321);
Calling a Method by Using Named Arguments Specify parameters by name: • Arguments can occur in any order • Omitted arguments are assigned default values if the corresponding parameter is optional Example void My. Method( int. Data, float. Data = 101. 1 F, int more. Int. Data = 99) {. . . } My. Method(more. Int. Data: 100, int. Data: 10); // float. Data is assigned default value
What Are Output Parameters? Output parameters enable you to pass a value back from a method to an argument: • Use the out keyword in the parameter list void My. Method(int first, double second, out int data) {. . . data = 99; } Call the method with a variable specified as an out argument int value; My. Method(10, 101. 1 F, out value); // value = 99
Lab: Declaring and Calling Methods • Exercise 1: Calculating the Greatest Common Divisor of Two Integers by Using Euclid’s Algorithm • Exercise 2: Calculating the GCD of Three, Four, or Five Integers • Exercise 3: Comparing the Efficiency of Two Algorithms • Exercise 4: Displaying Results Graphically • Exercise 5: Solving Simultaneous Equations (optional) Logon information Virtual machine 10266 A-GEN-DEV User name Student Password Pa$$w 0 rd Estimated time: 90 minutes
Lab Scenario
Lab Review Questions • When using output parameters in a method, what must you do before the method completes? • When adding optional parameters to an existing method signature, why will your code run successfully without making changes to any of the existing method calls? • When creating a unit test method in a Visual Studio test project, what attribute must you decorate your test method with?
Module Review and Takeaways • Review Questions • Best Practices