0% found this document useful (0 votes)
22 views64 pages

Inf1030 03 Methods and Behaviors

Uploaded by

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

Inf1030 03 Methods and Behaviors

Uploaded by

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

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

Table 3-1 C# access modifiers

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

• Call to method inside Main( ) method

WriteLine("Miles per gallon = {0:N2}",


CalculateMilesPerGallon(289,
12.2));
Actual 15
arguments
Parameters (continued)
• Like return types, parameters are
optional
– Keyword void not required (inside
parentheses) – when there are no
parameters
public void DisplayMessage( )
{
Write("This is ");
Write("an example of a method");
WriteLine("body.");
return; // no value is returned 16
}
Method Body
• Enclosed in curly braces
• Include statements ending in semicolons
– Declare variables
– Do arithmetic
– Call other methods
• Value-returning methods must include
return statement

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

Figure 3-3 IntelliSense display


22
Read( ) Method

23
Call Read( ) Methods
int aNumber;
Write("Enter a single character: ");
aNumber = Read( );
WriteLine("The value of the character entered: " +
aNumber);

Enter a single character: a


The value of the character entered: 97

24
Call Read( ) Methods
(continued)
int aNumber;
WriteLine("The value of the character entered: " +
(char) Read( ));
Explicit
cast

Enter a single character: a


The value of the character entered: a

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);

WriteLine("Your age next year” + " will be {0} ", +


+age);

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;

Write("Enter a value to be squared: ");


inputStringValue = ReadLine( );

31
aValue = double.Parse(inputStringValue);

result = Math.Pow(aValue, 2);

WriteLine("{0} squared is {1} ", aValue, result);


ReadKey( );
}
}
} // Curly braces should be lined up

32
Call Parse( ) (continued)
string sValue = " true ";
WriteLine (bool.Parse(sValue)); // displays True

string strValue = "q";


WriteLine(char.Parse(strValue)); // displays q

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( )

int newValue = Convert.ToInt32(stringValue);


35
Methods in the Math class

Table 3-2 Math


class methods
36
Math class (continued)

Table 3-2 Math


class methods
37
Math class (continued)

Table 3-2 Math


class methods
38
Math class (continued)

Table 3-2 Math


class methods
39
Math( ) Class
double aValue = 78.926; Each call
double result1, returns a value
result2;
result1 = Math.Floor(aValue); // result1 = 78
result2 = Math.Sqrt(aValue); // result2 =
8.88403061678651
Write("aValue rounded to 2 decimal places“ +
" is {0}", Math.Round(aValue, 2));

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);

WriteLine(" per Square Yard: {0:C}",


(squareYards * pricePerSquareYard));
}
• static method called from within the class
where it resides
44
• To invoke method → DisplayResults(16.5,
Value-Returning Method
• Has a return type other than void
• Must have a return statement
– Compatible value
• Zero, one, or more data items may be
passed as arguments
• Calls can be placed:
– In assignment statements
– In output statements
– In arithmetic expressions
– Or anywhere a value can be used

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);

// Note: cast required to avoid int division


return (feet + (double) inches / 12);
}
49
public static double GetPrice( )
{
string inputValue; // local variables
double price;
Write("Enter the price per Square Yard: ");
inputValue = ReadLine( );
price = double.Parse(inputValue);
return price;
}

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;
}

public static double DeterminePrice (double


squareYards,
double
pricePerSquareYard)
{
return (pricePerSquareYard * squareYards); 51
}
CarpetExampleWithClassMe
thods (continued)

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)

Figure 3-9 Call by reference versus value


58
Optional Parameters
• May assign default values to
parameters
– When you assign a default value to a
parameter, it then becomes an optional
parameter
public static void DoSomething(string name, int age =
21,
bool currentStudent = true, string
major = "CS")

• Can now call DoSomething( ) and send in


arguments for the default value or the
default values will be assigned to the
59
parameters
Coding Standards
• Naming conventions
• Spacing conventions
• Declaration conventions
• Commenting conventions

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

You might also like