6: MODULARIZING YOUR CODE: METHODS

6.1 Introduction to Methods 6.2 void Methods 6.3 Passing Arguments to Methods 6.4 Passing Arguments by Reference 6.5 Value-Returning Methods Console: methods & params

6.1 INTRODUCTION TO METHODS

Methods can be used to break a complex program into small, manageable pieces - AKA modularization - "Divide and Conquer" Two types of methods: - void method simply executes a group of statements and then terminates - value-returning method returns a value to the statement that called it Parameters are used to pass data INTO a method
   
  private void Hello() 
  { 
     MessageBox.Show( "Hello" ); 
  }
  
 
To call this method
 
  
  Hello(); // simply the name of the methos with parentheses indicating "method"

  

6.2 void METHODS

A void method simply executes the statement(s) it contains and then terminates. It does not return any value to the statement that called it To create a method you write its definition (header + body)
      // header: access mode, return type, method name and parameters 
      private void Hello( )
      
      // body: a collection of statements that are performed when the method is executed
      { 
        MessageBox.Show( "Hello" ); 
      }
      
      
Calling a Method A method executes ONLY when it is called Event handlers are methods called when specific events take place (button click) To call the "Hello" method:
   
   Hello(); // simply the name of the methos with parentheses indicating "method"
    
   
Declaring Method Inside a Class Methods usually belong to a class Visual C# methods typically belong to applications' default Form1 class Concept of Return Point The system jumps to the method and executes the statements in its body When the method ends, the system jumps back to the return point and resumes execution Top-Down Design To modularize a program, programmers commonly use a technique known as top-down design It breaks down an algorithm to methods The process is performed in the following manner: 1. The overall task is broken down into a series of subtasks 2. Each subtask is examined to determine whether it can be further broken down into more subtasks. 3. Once all the subtasks have been identified, they are written in code Simple Method (simple output message) Lights (change picture visibility & label text) About: methods, parameters, return

6.3 PASSING ARGUMENTS TO METHODS

An argument is any piece of data that is passed into a method when the method is called The MessageBox.Show method passes the string "Hello" as an argument:
      MessageBox.Show("Hello");  
      
   
A parameter is a variable that receives an argument that is passed into a method To create a method with a parameter, specify it in the parentheses
      // greets the person whose name is specified in 'Person'
      private void HelloYou( string Person )
      { 
        MessageBox.Show( "Hello " + Person ); 
      }
      
      
Calling a Method - method executes ONLY when it is called - event handlers are methods called when specific events take place (button click) - To call the "HelloYou" method:
   
   HelloYou("Lauren"); // passes in "Lauren"
   
   
OR...
   
   string s;
   s = "Lance";
   HelloYou( s ); // passes in "Lance"
   
   
OR...
   
   string s - txtFirstName.Text + " " + txtLastName.Text;
   HelloYou( s ); // passes in whatever is in the two textBoxes
   
   

This method displays an int value:
      private void DisplayValue(int value) // value is an int parameter:
      {
         MessageBox.Show(value.ToString());
      }  
      
      
A call to DisplayValue method with 5 as parameter is:
      DisplayValue(5);  // 5 is passed into the DisplayValue method  
      
   
Methods with Arguments (pass an int value) You can pass the contents of variables as arguments.
      int x = 5;
      DisplayValue(x);
      DisplayValue(x * 4);
      
   
In this example, x is an int variable with a value 5. Its contents are passed as argument. The expression x * 4 also produces an int results, which can also be passed as argument Another example:
      DisplayValue(int.Parse("700"));
      
    
Argument and Parameter Data Type Compatibility (implicit conversion) An argument's data type must be assignment compatible with the receiving parameter's data type - can pass only string arguments into string parameter - can pass int arguments into int parameters, but cannot pass double or decimal arguments into int parameters - can pass double or int arguments to double parameters, but cannot pass decimal values to double parameters - can pass decimal or int arguments to decimal parameters, but cannot pass double arguments into decimal parameters
Passing Multiple Arguments You can pass more than one argument to a method Normally multiple arguments are passed in a list separated by commas.
         // button click method is called from event
         private void showButton_Click(object sender, EventArgs e)
         {
           ShowName("Suzanne", "Smith");
         }
         
         
         // ShowName method has TWO parameters
         private void ShowName(string firstName, string lastName)
         {
           MessageBox.Show(firstName + " " + lastName);
         }  
         
         
C# also allows you to specify which parameter an argument should be passed into. (By Name) The syntax is: parameterName : value An argument that is written using this syntax is known as a named argument
         // button click method is called from event
         private void showButton_Click(object sender, EventArgs e)
         {
           ShowName(lastName : "Smith", firstName : "Suzanne"); // named arguments
         }
         
         
         // ShowName method has TWO parameters
         private void ShowName(string firstName, string lastName)
         {
           MessageBox.Show(firstName + " " + lastName);
         }  
         
         
North America Notice that you get the same result as before.
Default Arguments C# allows you to provide a default argument for a method parameter
         private void ShowTax(decimal price, decimal taxRate = 0.07m) 
         { 
          decimal tax = price * taxRate;
         }  
         
         
The value of taxRate is defaulted to 0.07m. You can simply call the method by passing only the price
            ShowTax(100.0m);  
            
            
You can also override the default argument
            ShowTax(100.0m, 0.08m);  
            
            
Cards (switch, listbox selection, parameter) Pass By Value (COPY the parameter value)

6.4 PASSING ARGUMENTS BY REFERENCE

A reference parameter is a special parameter that does not receive a copy of the argument's value It becomes a reference to the argument that was passed into it When an argument is passed by reference to a method, the method can change the value of the argument in the calling part of the program In C#, you declare a reference parameter by writing the ref keyword before the parameter variable's data type
      private void SetToZero(ref int number)
      {
        number =0;
      }  
      
      
To call a method that has a reference parameter, you also use the keyword ref before the argument
      int myVar = 99;
      SetToZero(ref myVar); 

      
Using Output Parameters An output parameter works like a reference parameter with the following differences: An argument does not have to be a value before it is passed into an output parameter A method that has an output parameter must be the output parameter to some value before it finishes executing In C#, you declare an output parameter by writing the out keyword before the parameter variable's data type
         private void SetToZero(out int number)
         {
          number = 0;
         }  
         
         
To call a method that has a output parameter, you also use the keyword out before the argument
         int myVar;         
         SetToZero(out myVar);  
         
         
Pass By Reference (REF allows changes to parameters) Pay and Bonus

6.5 VALUE-RETURNING METHODS

A value-returning method is a method that returns a value to the part of the program that called it A value-returning method is like a void method in the following ways: It contains a group of statements that performs a specific task When you want to execute the method, you call it The .NET Framework provide many value-returning methods, for example, the int.Parse method that accepts a string and returns an int value int number = int.Parse("100");0 Sum: Value Returning Cups to Ounces Write Your Own Value-Returning Functions In C# the generic format is: AccessModifier DataType MethodName(ParameterList) { statement(s); return expression; } AccessModifier: private or public DataType: int, double, decimal, string, and Boolean MethodName: the identifier of the method; must be unique in a program ParameterList: an optional list of parameter Expression: can be any value, variable, or expression that has a value The Return Statement There must be a return statement inside the method which is usually the last statement of the method. This return statement is used to return a value to the statement that called the method.
      private int Sum(int num1, int num2)
      {
        return num1 + num2; // Note that the returned value and the method's type must match
      }

      
      // int type
      private int Sum(int num1, int num2)
      { 
        return num1 + num2;
      }

      
      // double type
      private double Sum(double num1, double num2)
      { 
        return num1 + num2;
      }

      
      // decimal type
      private decimal Sum(decimal num1, decimal num2)
      { 
        return num1 + num2;
      }  
      
      
Return Values to Variables A value-returning method returns a value with specific type. However, the method no longer keeps the value once it is returned. Declare a variable to hold the returned value to use the value over and over again
      int combinedAge = Sum (userAge, friendAge);

      private int Sum(int num1, int num2)
      {
        return num1 + num2;
      }   
      
      
After execution, the value is kept in combinedAge variable
   private bool IsEven(int number) // boolean method returns either true or false
   {
      bool numberIsEven;
      if (number % 2 == 0) 
      {
         numberIsEven = true;
      }
      else 
      {
         numberIsEven = false;
      }
      return numberIsEven;
   }  
   
   
Using Modulus Operator in Boolean Expressions Use the modulus operator to determine if a whole number is odd or even number % 2 When a number modulus 2, there are only two possible outcomes: 0 and 1 Returning a String from a Method String is a primitive data type. A C# value-returning method can return a string to the statement that called it. For example,
         private string FullName(string first, string middle, string last)
         {
            return first + " " + middle + " " + last;
         }  
         
         
A sample statement to call it is:
         FullName("Lynn","Alisha","McCormick");  
         
         
Full Name (strings)