CSC221 Lecture 4
CSC221 Lecture 4
Introduction to Methods
Void Methods
Passing Arguments to Methods
Passing Arguments by Reference
Debugging Methods
Introduction to Methods
Methods can be used to break a complex program into small,
manageable pieces.
A void method simply executes a group of statements and then terminates.
A value-returning method returns a value to the statement that called it.
For example, if you have a method that calculates the maximum value
in an array, you can use this method from any point in your code, and
use the same lines of code in each case.
This concept is referred to as reusability.
Advantages of Method
Methods make your code more readable, as you can use them to
group related code together, thereby reducing the length of your code.
Methods can also be used to create multipurpose code, enabling them
to perform the same operations on varying data.
For example, you could supply an array to search as a parameter and obtain the
maximum value in the array as a return value. This means that you can use the
same method to work with a different array each time.
Methods
6
Method Definition
7
Method Header Components
Access modifier - The keyword private is an access modifier. When a method is
declared as private, it can be called only by code inside the same class as the
method.
Return type (void) - It does not return a value back to the statement that called it.
Method name - The method in this example is named DisplayMessage, so we
can easily guess what the method does: It displays a message.
Parentheses - In the header, the method name is always followed by a set of
parentheses.
Note: The method header is never terminated with a semicolon.
8
The Method Body
9
Calling a Method
A method executes when it is called. Event handlers are called when
specific events take place, but other methods are executed by method
call statements.
When a method is called, the program branches to that method execute
the statements in its body.
Here is an example of a method call statement that calls the
DisplayMessage method we previously examined:
DisplayMessage(); 10
11
Class Task 1: The Simple Method application’s form
namespace Simple_Method
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
13
private void DisplayValue(int value)
{
MessageBox.Show(value.ToString()); Parameter
}
// Things in between …
15
Example/Class Activity
16
private void button1_Click(object sender, EventArgs e)
{
int input;
string output;
if (int.TryParse(textBox1.Text, out input))
{
output = getBinaryValue(input);
textBox2.Text = output;
}
else
{
MessageBox.Show("Input is not an integer value, try again");
}
}
return output;
}
20
private void ShowTax(decimal price, decimal taxRate = 0.07m)
{
// Calculate the tax.
decimal tax = price * taxRate;
// Display the tax.
MessageBox.Show("The tax is " + tax.ToString("c"));
}
“Compute” button 22
1 2
3
Can you explain the outputs?
Different outputs, Outputs (1) and (3) used 0.07 as the tax rate! 23
Passing Arguments by Value
24
private void goButton_Click(object sender, EventArgs e)
{
int number = 99;
// Display the value of number.
MessageBox.Show("The value of number is " + number);
// Call ChangeMe, passing number as an argument.
ChangeMe(number);
// Display the value of number again.
MessageBox.Show("The value of number is " + number);
}
In C#, you declare a reference parameter by writing the ref keyword before the parameter variable’s data type.
When you call a method that has a reference parameter, you must also write the keyword ref before the argument.
The following code sample shows an example:
Example 29
Boolean Methods
A Boolean method returns either true or false. You can use a Boolean
method to test a condition, and then return either true or false to indicate
whether the condition exists.
Boolean methods are useful for simplifying complex conditions that are
tested in decision and repetition structures.
30
private bool IsEven(int number)
{
// Local variable to hold true or false
bool numberIsEven;
// Determine whether the number is even.
if (number % 2 == 0)
{
numberIsEven = true;
}
else
{
numberIsEven = false;
}
// Return the result.
return numberIsEven;
}
• If a salesman sells $100,000 in revenue while working with a company that pays
5 percent of the revenue, his commission check will be $5,000.
• If a salesman sells $100,000 in revenue while working with a company that pays
8 percent of the revenue, his commission check will be $8,000.
The program should have a method named CalculateCommission that receives the
revenue sale by a salesman and the commission percentage as arguments, and returns
the commission earned by the salesman.
37
Question 2
Cups and fluid ounces are common units of measurement for food items. Sometimes,
when a recipe calls for an item measured in cups, you find that in the grocery store the
item is sold in fluid ounces. To know how much you need to purchase for the recipe,
you need to convert the required number of cups to fluid ounces. The formula is:
Ounces = Cups × 8
Create an application with a form similar to the one shown in the figure on the next
slide.
The user enters the number of cup(s) into text box. When the user clicks the Convert
button, the application should display the equivalent value of Ounces in a Label field.
38
Figure for Question 2 39
Question 3
Kinetic Energy
In physics, an object that is in motion is said to have kinetic energy. The following
formula can be used to determine a moving object’s kinetic energy:
In the formula KE is the kinetic energy, m is the object’s mass in kilograms, and v is
the object’s velocity in meters per second. Create an application that allows the user
to enter an object’s mass and velocity and then displays the object’s kinetic energy.
The application should have a method named KineticEnergy that accepts an object’s
mass (in kilograms) and velocity (in meters per second) as arguments. The method
should return the amount of kinetic energy that the object has. 40