Chapter 06+W10
Chapter 06+W10
6.1 – 6.3
Modularizing Your
Code with Methods
Topics
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
6.6 Debugging Methods
6.1 Introduction to Methods
• Methods can be used to break a complex program into
small, manageable pieces
– This approach is known as divide and conquer
– In general terms, breaking down a program to smaller units of
code, such as methods, is known as modularization
• Two types of methods are:
– 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
Example
Using one long sequence of statement to perform a task
Namespace Example
{
public partial class Form1 : Form
{
private void myButton_Click(object sender, EventArgs e)
{
statement;
statement;
statement;
statement;
statement;
statement;
…
}
}
}
Example
Using methods to divide and conquer a problem
Namespace Example
{
public partial class Form1 : Form
{
private void myButton_Click(object sender, EventArgs e)
{
Method2();
Method3();
…
}
namespace Example
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MessageBox.Show("Hello");
• A parameter is a variable that receives an argument that is passed into a
method
– In the following, value is an int parameter:
• Notice that you get the same result if the call statement is:
showName("Suzanne", "Smith");
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);