0% found this document useful (0 votes)
12 views40 pages

Chapter 06 Gaddis CSharp 6e F24 V2

Uploaded by

jomarrodz872
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views40 pages

Chapter 06 Gaddis CSharp 6e F24 V2

Uploaded by

jomarrodz872
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Starting out with Visual C#

Sixth Edition

Chapter 6
Modularizing Your Code
with Methods

This Photo by Unknown Author is licensed under CC BY-SA

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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 executes a group of
statements and then returns a value to the statement
that called it

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Example (1 of 2)
Using one long sequence of statements to perform a task

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
This Photo by Unknown Author is licensed under CC BY
Example (2 of 2)
Using methods to divide and conquer a problem

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.2 void Methods
• A void method simply executes the statement 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
• A method definition has two parts:
– header: the method header appears at the beginning
of a method definition to indicate the access mode,
return type, and method name
– body: the method body is a collection of statements
that are performed when the method is executed

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
The Method Header (1 of 2)
• The book separates a method header into four parts :
– Access modifier: keyword that defines the access control
▪ private: a private method can be called only by code
inside the same class as the method
▪ public: a public method can be called by code that is
outside the class.
– Return type: specifies whether or not a method returns a value
– Method name: the identifier of the method; must be unique in a
given program. This book uses Pascal case (aka camelCase)
– Parentheses: A method's name is always followed by a pair of
parentheses

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
The Method Header (2 of 2)

Access Return Method Parentheses


Modifier Type Name

private void DisplayMessage()


{
MessageBox.Show("This is the DisplayMessage method.");
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Declaring Method Inside a Class (1 of 2)

• Methods usually belong to a class


• All Visual C# methods typically belong to the application’s
default Form1 class (GUI Apps)
• In this book, methods are created inside the Form1 class

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Declaring Method Inside a Class (2 of 2)
namespace Example
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

// Your method definitions will appear here, inside Form1 class.


}
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Calling a Method (1 of 2)
• A method executes whenever it is called
• Event handlers are called when specific events take
place when events occur (e.g., a click). However,
methods are executed by method call statements.
• A method call statement is the name of the method
followed by a pair of parentheses.
• For example: (see next slide)

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Calling a Method (2 of 2)
private void goButton_Click(object sender, EventArgs e)
{
MessageBox.Show("This is the goButton_Click method.");
DisplayMessage();
}

private void DisplayMessage()


{
MessageBox.Show("This is the DisplayMessage method.");
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Concept of Return Point

• When calling a method, the system needs to know where


the program should return after the method ends
• The system saves the memory address of the location,
called the return point, to which it should return
• 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

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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:
– The overall task that the program is to perform is broken
down into a series of subtasks
– Each subtask is examined to determine whether it can be
further broken down into more subtasks. This step is
repeated until no more subtasks can be identified
– Once all the subtasks have been identified, they are
written in code as methods

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.3 Passing Arguments to Methods
• An argument is any piece of data that is passed into a method when the
method is called
– In the following, the statement calls the MessageBox.Show method
and 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
– In the following, value is an int parameter:

private void DisplayValue(int value)


{
MessageBox.Show(value.ToString());
}

– An example of a call to the DisplayValue method with 5 as the argument is:


DisplayValue(5);

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Contents of Variables as Arguments
• You can pass the contents of variables as arguments. For example,
private void DisplayValue(int value)
{
MessageBox.Show(value.ToString()); int x = 5;
} DisplayValue(x);
DisplayValue(x * 4);

• value is an int parameter in the DisplayValue method

• In this example, x is an int variable with the value 5. Its contents are
passed as an argument.

• The expression X * 4 also produces an int result, which can be


passed as an argument

• Another example is: DisplayValue(int.Parse("700"));

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Argument and Parameter Data Type
Compatibility
• An argument’s data type must be assignment compatible with the
receiving parameter's data type
• Basically,
– You can pass only string arguments into string parameters
– You can pass int arguments into int parameters, but you
cannot pass double or decimal arguments into int
parameters
– You can pass either double or int arguments to double
parameters, but you cannot pass decimal values to double
parameters
– You can pass either decimal or int arguments to decimal
parameters, but you cannot pass double arguments into
decimal parameters

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Passing Multiple Arguments
• To accept multiple arguments, a method must have multiple
parameters
• The following method accepts two arguments:

private void Add(int num1, int num2)


{
int sum = num1 + num2;
MessageBox.Show(sum.ToString());
}

• The following statement calls the Add method, passing 10 and 20 as


arguments:
Add(10, 20);

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Passing Multiple Arguments
• In this example, the argument 10 is passed to the num1
parameter and the argument 20 is passed to the num2
parameter
Add(10, 20);

private void Add(int num1, int num2)


{
int sum = num1 + num2;
MessageBox.Show(sum.ToString());
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Named Arguments
• In the method call, you can specify which parameter an argument
should be passed into. The syntax is:

parameterName : value

• Look at the following method:


private void ShowName(string firstName, string lastName)
{
MessageBox.Show(firstName + " " + lastName);
}

• The following statements call the method with named arguments:

ShowName(firstName: "Kiran", lastName: "Sharma");


ShowName(lastName: "Sharma", firstName: "Kiran");

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Default Arguments
• You can provide a default argument for a parameter in the method
header:
private void ShowTax(decimal price, decimal taxRate = 0.07m)
{
decimal tax = price * taxRate;
MessageBox.Show("The tax is " + tax.ToString("c"));
}

• The value of taxRate is defaulted to 0.07m. You can simply call the
method by passing only the price
ShowTax(100.0m); // taxRate will assume the default value of 0.07m

• You can also override the default argument

ShowTax(100.0m, 0.08m);

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.4 Passing Arguments by Reference (1 of 2)
• A reference parameter is a special type of 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;
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.4 Passing Arguments by Reference (2 of 2)
• To call a method that has a reference parameter, you also use the
keyword ref before the argument

int myVar = 99;


SetToZero(ref myVar);

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Using Output Parameters (1 of 2)
• 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 set 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;
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Using Output Parameters (2 of 2)
• To call a method that has an output parameter, you also use the
keyword out before the argument

int myVar;
SetToZero(out myVar);

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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
• .NET provides many value-returning methods. For example, the
int.Parse method accepts a string and returns an int value

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Write Your Own Value-Returning
Functions
• In C# the generic format for writing a value-returning function is:

• AccessModifier: private or public

• DataType: int, double, decimal, string, bool, etc.

• 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

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
The return Statement
• There must be a return statement inside the method. It is
usually the last statement of the method. This return
statement is used to return a value to the statement that called
the method. For example:

private int Sum(int num1, int num2)


{
return num1 + num2;
}

• Notice that the returned value and the method’s type must
match
– In the above example, the method is an int method, so it
can only return int value

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Sample Code
// 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;
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Returning 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.
• You can 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 the combinedAge


variable

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Boolean Methods (1 of 2)
• A Boolean method returns either true or false. You
can use a Boolean method to test a condition
private bool IsEven(int number)
{
bool numberIsEven;

if (number % 2 == 0)
{
numberIsEven = true;
}
else
{
numberIsEven = false;
}

return numberIsEven;
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Boolean Methods (2 of 2)
• With this code, an int value assigned to the number
parameter will be evaluated by the if statement
• The return statement will return either true or false
private bool IsEven(int number)
{
bool numberIsEven;

if (number % 2 == 0)
{
numberIsEven = true;
}
else
{
numberIsEven = false;
}

return numberIsEven;
}

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
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 this method is:


string fullName = FullName("Martina", "Isabella", "Gomez");

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.6 Debugging Methods

This Photo by Unknown Author is licensed under CC BY-SA

This Photo by Unknown Author


is licensed under CC BY-NC

Rubber Duck Debugging - How to Solve a Problem


https://youtu.be/NBgIHOrjSxs?si=knM0FjHkMkKk0beG

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.6 Debugging Methods (1 of 4)
• The Step Into command allows you to single-step
through a called method.
• Execute the Step Into command in any of the following
ways:
– Press the F11 key
– Select Debug from the menu bar, and then select
Step Into from the Debug menu
– Click the Step Into button on the Debug Toolbar, if
the toolbar is visible
• Tutorial 6-6 demonstrates the Step Into command.
Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.6 Debugging Methods (2 of 4)
• The Step Over command allows you to call a method
without single-stepping through its statements.
• Execute the Step Over command in any of the following
ways:
– Press the F10 key
– Select Debug from the menu bar, and then select
Step Over from the Debug menu
– Click the Step Over button on the Debug Toolbar, if
the toolbar is visible
• Tutorial 6-7 demonstrates the Step Over command.

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.6 Debugging Methods (3 of 4)
• When single-stepping through a method, the Step Out
command causes the rest of the method's statements to
execute without single-stepping.
• Execute the Step Out command in any of the following ways:
– Press the Shift + F11 keys
– Select Debug from the menu bar, and then select Step
Out from the Debug menu
– Click the Step Out button on the Debug Toolbar, if the
toolbar is visible

• Tutorial 6-8 demonstrates the Step Out command.

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
6.6 Debugging Methods (4 of 4)
• Visual Studio can be configured in different ways.
– Under some configurations, the Step Into command
from the Debug menu might be activated by the F8
function key.
– Under some configurations, the Step Over command
may be activated by the Shift + F8 keys.
– Under some configurations, the Step Out command
might be activated by the Ctrl + Shift + F8 keys.
• To find out which keys are used, look carefully at these
commands when you click on the Debug menu.

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved
Copyright

Copyright © 2023, 2017, 2014, 2012 Pearson Education, Inc. All Rights Reserved

You might also like