Inf1030 03 Methods and Behaviors
Inf1030 03 Methods and Behaviors
1
Objectives
• Become familiar with the components of
a method
• Call class methods with and without
parameters
• Use predefined methods in the Console
and Math classes
• Write your own value- and nonvalue-
returning class methods (with and
without parameters)
• Distinguish between value, ref, and out
parameter types
2
Objectives (continued)
• Explore the use of optional parameters
with default values
3
Anatomy of a Method
• Methods defined inside classes
• Group program statements
– Based on functionality
– Called one or more times
• All programs consist of at least one
method
– Main( )
• User-defined method
4
/* SquareExample.cs Author: */
using System;
using static System.Console;
namespace Square
{
public class SquareExample
Required method
{
public static void Main( )
{
int aValue = 789;
int result;
result = aValue * aValue;
WriteLine("{0} squared is {1}", aValue, result);
ReadKey( );
}
}
}
5
Anatomy of a Method
(continued)
6
Modifiers
• Appear in method headings
• Appear in the declaration heading for
classes and other class members
• Indicate how it can be accessed
• Types of modifiers
– static
– Access
7
static Modifier
• Indicates member belongs to the type
itself rather than to a specific object of a
class
• Main( ) must include static in heading
• Methods that use static modifier - class
methods
– Instance methods require an object
• Members of the Math class are static
– public static double Pow(double, double)
– double answer = Math.Sqrt(25);
8
Access Modifiers
• public
• protected
• internal
• protected internal
• private
9
Level of Accessibility
10
Return Type
• Indicates what type of value is returned
when the method is completed
• Always listed immediately before
method name
• void
– No value being returned
• return statement
– Required for all non-void methods
– Compatible value
11
Return Type (continued)
Return
type
public static double CalculateMilesPerGallon
(int milesTraveled, double gallonsUsed)
{
return milesTraveled / gallonsUsed;
}
Compatible value
(double) returned
12
Method Names
• Follow the rules for creating an identifier
– Pascal case style
– Action verb or prepositional phrase
• Examples
– CalculateSalesTax( )
– AssignSectionNumber( )
– DisplayResults( )
– InputAge( )
– ConvertInputValue( )
13
Parameters
• Supply unique data to method
• Appear inside parentheses
– Include data type and an identifier
• In method body, reference values using
identifier name
– Parameter refers to items appearing in
the heading
– Argument for items appearing in the call
• Formal parameters
• Actual arguments
14
Parameters (continued)
public static double CalculateMilesPerGallon
(int milesTraveled, double gallonsUsed)
{
return milesTraveled / gallonsUsed; Two formal
} parameters
17
Calling Class Methods
• Also called invoking a method
• Call to method that returns no value
[qualifier].MethodName(argumentList);
• Qualifier
– Square brackets indicate optional
– Class or object name
• Call to method does not include data
type
• Use IntelliSense
18
IntelliSense
After typing the dot, list
of members pops up
Method signature(s)
and description
3-D box —
member methods
19
Predefined Methods
• C# has extensive class library
– Classes have number of predefined
methods
• Console class (in System namespace)
– Overloaded methods
• Multiple methods with same name, but
each has different number or type of
parameter
20
Predefined Methods
• Console class
– Overloaded methods
• Write( )
• WriteLine( )
– Read( )
• Not overloaded
• Returns an integer
21
IntelliSense Display
string argument
expected
string
parameter
18 different Write( )
methods
23
Call Read( ) Methods
int aNumber;
Write("Enter a single character: ");
aNumber = Read( );
WriteLine("The value of the character entered: " +
aNumber);
24
Call Read( ) Methods
(continued)
int aNumber;
WriteLine("The value of the character entered: " +
(char) Read( ));
Explicit
cast
25
ReadLine( )
• Returns string
• Not overloaded
• Returns characters entered up to the
enter key
• String value must be parsed
26
/* AgeIncrementer.cs Author: */
using System;
using static System.Console;
namespace AgeExample
{
public class AgeIncrementer
{
public static void Main( )
{
int age;
string aValue;
27
Write("Enter your age: ");
aValue = ReadLine( );
age = int.Parse(aValue);
ReadKey( );
}
}
}
28
ReadKey( )
• Obtains next character entered by user
• Used to hold screen
• Can be called if you want to allow user
to press any key after they finished
reading
• Not overloaded
ReadKey( );
29
Call Parse( )
• Predefined static method
• All numeric types have a Parse( )
method
– double.Parse("string number")
– int.Parse("string number")
– char.Parse("string number")
– bool.Parse("string number")
• Expects string argument
– Argument must be a number – string
format
• Returns the number (or char or bool) 30
/* SquareInputValue.cs Author: */
using System;
using static System.Console;
namespace Square
{
class SquareInputValue
{
static void Main( )
{
string inputStringValue;
double aValue, result;
31
aValue = double.Parse(inputStringValue);
32
Call Parse( ) (continued)
string sValue = " true ";
WriteLine (bool.Parse(sValue)); // displays True
33
Call Parse( ) with
Incompatible Value
• WriteLine(char.Parse(sValue));
when sValue referenced “True”
34
Convert Class
• More than one way to convert from one
base type to another
– System namespace — Convert class — static
methods
– Convert.ToDouble( )
– Convert.ToDecimal( )
– Convert.ToInt32( )
– Convert.ToBoolean( )
– Convert.ToChar( )
aValue rounded to 2
decimal places is 78.93
40
Method Calls That Return
Values
Line 1 int aValue = 200; In an assignment
Line 2 int bValue = 896; statement
Line 3 int result;
Line 4 result = Math.Max(aValue, bValue); // result = 896
Line 5 result += bValue * Part of arithmetic expression
Line 6 Math.Max(aValue, bValue) – aValue;
// result = 896 + (896 * 896 - 200) (result =
803512)
Line 7 WriteLine("Largest value between {0} " +
Line 8 "and {1} is {2}", aValue, bValue,
Line 9 Math.Max(aValue, bValue));
Argument to
another method call
41
Writing Your Own Class
Methods
[modifier(s)]
returnType MethodName ( parameterList )
{
// body of method - consisting of executable
statements
}
• void Methods
– Simplest to write
– No return statement
42
Writing Your Own Class
Methods – void Types
class
Call to this method
method
looks like:
DisplayInstructions( );
public static void DisplayInstructions( )
{
WriteLine("This program will determine how “ +
"much carpet to purchase.");
WriteLine( );
WriteLine("You will be asked to enter the “ +
" size of the room and ");
WriteLine("the price of the carpet, “ +
"in price per square yards.");
WriteLine( );
}
43
Writing Your Own Class
Methods – void Types
( continued)
public static void DisplayResults(double squareYards,
double
pricePerSquareYard)
{
Write("Total Square Yards needed: ");
WriteLine("{0:N2}", squareYards);
Write("Total Cost at {0:C} ", pricePerSquareYard);
45
Value-Returning Method
(continued)
public static double GetLength( )
{
string inputValue; Return type → double
int feet, inches;
Write("Enter the Length in feet: ");
inputValue = ReadLine( );
feet = int.Parse(inputValue);
Write("Enter the Length in inches: ");
inputValue = ReadLine( );
inches = int.Parse(inputValue); double returned
return (feet + (double) inches / 12);
}
46
CarpetExampleWithClassMe
thods
/* CarpetExampleWithClassMethods.cs */
using System;
using static System.Console;
namespace CarpetExampleWithClassMethods
{
public class CarpetWithClassMethods
{
public static void Main( )
{
double roomWidth, roomLength,
pricePerSqYard,
noOfSquareYards;
DisplayInstructions( ); 47
// Call getDimension( ) to get length
roomLength = GetDimension("Length");
roomWidth = GetDimension("Width");
pricePerSqYard = GetPrice( );
noOfSquareYards =
DetermineSquareYards(roomWidth,
roomLength);
DisplayResults(noOfSquareYards,
pricePerSqYard);
} // End of Main ( )
48
public static double GetDimension(string side )
{
string inputValue; // local variables
int feet, // needed only by this
inches; // method
Write("Enter the {0} in feet: ", side);
inputValue = ReadLine( );
feet = int.Parse(inputValue);
Write("Enter the {0} in inches: ", side);
inputValue = ReadLine( );
inches = int.Parse(inputValue);
50
public static double DetermineSquareYards
(double width, double length)
{
const int SQ_FT_PER_SQ_YARD = 9;
double noOfSquareYards;
noOfSquareYards = length * width /
SQ_FT_PER_SQ_YARD;
return noOfSquareYards;
}
52
Types of Parameters
• Call by value
– Copy of the original value is made
• Other types of parameters
– ref
– out
– params
• ref and out cause a method to refer to
the same variable that was passed into
the method
53
Parameters Example
// Code pulled from Parameters.cs solutions
int testValue = 1;
TestDefault(testValue);
WriteLine("Upon return from TestDefault “ +
"Value: {0}", testValue);
Upon return
WriteLine( );
from
TestDefault
public static void TestDefault(int aValue) Value: 1
{
aValue = 111;
WriteLine("In TestDefault - Value: {0}", aValue);
}
54
Parameters Example
(continued)
// Code pulled from Parameters.cs solutions
int testValue = 1;
TestRef(ref testValue);
WriteLine("Upon return from TestRef “ +
"Value: {0}", testValue); Upon return
WriteLine( ); from
TestRef
public static void TestRef (ref int aValue) Value: 333
{
aValue = 333;
WriteLine("In TestRef - Value: {0}", aValue);
}
55
Parameters Example
(continued)
// Code pulled from Parameters.cs solutions
int testValue;
TestOut(out testValue);
WriteLine("Upon return from TestOut “ +
"Value: {0}", testValue);
WriteLine( ); Upon return
from
TestOut
public static void TestOut (out int aValue) Value: 222
{
aValue = 222;
WriteLine("In TestOut - Value: {0}", aValue);
}
56
Parameters.cs
57
Types of Parameters
(continued)
60
Resources
C# Dev Center –
http://www.csharp.net
Code Gallery site –
http://code.msdn.microsoft.com
Methods (C# Programming Guide) –
http://msdn.microsoft.com/en-us/library/ms173114.aspx
61
Summary
• Components of a method
• Class methods
– Parameters
• Predefined methods
• Value- and nonvalue-returning methods
62
Summary (continued)
• Types of parameters
• Optional parameters
• Named parameters
63
Questions?
64