Sei sulla pagina 1di 27

1

Chapter 6 - Methods
Outline
6.1 Introduction
6.2 Program Modules in C#
6.3 Math Class Methods
6.4 Methods
6.5 Method Definitions
6.6 Argument Promotion
6.7 C# Namespaces
6.8 Value Types and Reference Types
6.9 Passing Arguments: Call-by-Value vs. Call-by-Reference
6.10 Random-Number Generation
6.11 Example: Game of Chance
6.12 Duration of Identifiers
6.13 Scope Rules
6.14 Recursion
6.15 Example Using Recursion: The Fibonacci Series
6.16 Recursion vs. Iteration
6.17 Method Overloading

 2002 Prentice Hall. All rights reserved.


2

6.2 Program Modules in C#

• Modules
– Class
– Method
– Enables use of classes or methods without knowledge of
how they work, just what they should do
• The .NET Framework Class Library (FCL)
– Helps to increase reusability
– Console
– MessageBox

 2002 Prentice Hall. All rights reserved.


3

6.2 Program Modules in C#

boss

worker1 worker2 worker3

worker4 worker5

Fig. 6.1 Hierarchical boss method/worker method relationship.

 2002 Prentice Hall. All rights reserved.


4

6.3 Math Class Methods

• The Math class


– Allows the user to perform common math calculations
– Using methods
• ClassName.MethodName( argument1, arument2, … )
• List of methods are in Fig. 6.2
– Constants
• Math.PI = 3.1415926535…
• Math.E = 2.7182818285…

 2002 Prentice Hall. All rights reserved.


5

6.3 Math Class Methods

M e th o d De sc rip tio n Exa m p le


Abs( x ) absolute value of x Abs( 23.7 ) is 23.7
Abs( 0 ) is 0
Abs( -23.7 ) is 23.7

Ceiling( x ) rounds x to the smallest integer Ceiling( 9.2 ) is 10.0


not less than x Ceiling( -9.8 ) is -9.0
Cos( x ) trigonometric cosine of x Cos( 0.0 ) is 1.0
(x in radians)
Exp( x ) exponential method ex Exp( 1.0 ) is approximately
2.7182818284590451
Exp( 2.0 ) is approximately
7.3890560989306504
Floor( x ) rounds x to the largest integer not Floor( 9.2 ) is 9.0
greater than x Floor( -9.8 ) is -10.0
Log( x ) natural logarithm of x (base e) Log( 2.7182818284590451 )
is approximately 1.0
Log( 7.3890560989306504 )
is approximately 2.0
Max( x, y ) larger value of x and y Max( 2.3, 12.7 ) is 12.7
(also has versions for float, Max( -2.3, -12.7 ) is -2.3
int and long values)
Min( x, y ) smaller value of x and y Min( 2.3, 12.7 ) is 2.3
(also has versions for float, Min( -2.3, -12.7 ) is -12.7
int and long values)
Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0
Pow( 9.0, .5 ) is 3.0
Sin( x ) trigonometric sine of x Sin( 0.0 ) is 0.0
(x in radians)
Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0
Sqrt( 9.0 ) is 3.0
Tan( x ) trigonometric tangent of x Tan( 0.0 ) is 0.0
(x in radians)
Fig. 6.2 C o m m o nly use d Math c la ss m e t ho d s.

 2002 Prentice Hall. All rights reserved.


6

6.4 Methods

• Variables
– Declared in a method = local variables
– Declared outside a method = global variables
– Only the method that defines them know they exist
• Send parameters to communicate with other methods
• Reasons for using
– Divide and conquer
– Reusability
• Use classes and methods as building blocks for new ones
– Cut down on repetition
• Methods can be called from anywhere in a program

 2002 Prentice Hall. All rights reserved.


7

6.5 Method Definitions

• Writing a custom method


– Header
• ReturnType Properties Name( Param1, Param2, … )
– Body
• Contains the code of what the method does
• Contains the return value if necessary
– For uses call elsewhere in program
• Pass parameters if needed
– All methods must be defined inside of a class

 2002 Prentice Hall. All rights reserved.


8
1 // Fig. 6.4: MaximumValue.cs Outline
2 // Finding the maximum of three doubles.
3
4 using System;
5 MaximumValue.cs
6 class MaximumValue
7 {
8 // main entry point for application
9 static void Main( string[] args )
10 {
11 // obtain user input and convert to double
12 Console.Write( "Enter first floating-point value: " ); The program gets three
13 double number1 = Double.Parse( Console.ReadLine() ); values from the user
14
15 Console.Write( "Enter second floating-point value: " );
16 double number2 = Double.Parse( Console.ReadLine() );
17
18 Console.Write( "Enter third floating-point value: " );
19 double number3 = Double.Parse( Console.ReadLine() );
20
21 // call method Maximum to determine largest value
22 double max = Maximum( number1, number2, number3 );
23
24 // display maximum value The three values are then passed
25 Console.WriteLine("\nmaximum is: " + max );
26 to the Maximum method for use
27 } // end method Main

 2002 Prentice Hall.


All rights reserved.
9
28 Outline
29 // Maximum method uses method Math.Max to help determine
30 // the maximum value
31 static double Maximum( double x, double y, double z )
32 { MaximumValue.cs
33 return Math.Max( x, Math.Max( y, z ) );
34
35 } // end method Maximum
36
37 } // end class MaximumValue
The Maximum method receives 3
variables and returns the largest one

The use of Math.Max uses the Max


method in class Math. The dot
operator is used to call it.

Enter first floating-point value: 37.3


Enter second floating-point value: 99.32 Program Output
Enter third floating-point value: 27.1928

maximum is: 99.32

 2002 Prentice Hall.


All rights reserved.
10

6.6 Argument Promotion

• Implicit Conversion
– Object is converted to a needed type implicitly
– Only done if complier knows no data will be lost
• Explicit Conversion
– Object is manually converted
– Required if there could be a loss of data
– Widening
• Make an object that of a derived class and more complex
– Narrowing
• Make an object that of a base class and cause some data loss

 2002 Prentice Hall. All rights reserved.


11

6.6 Argument Promotion

Typ e Ca n b e C o nverted to Typ e(s)


bool object
byte decimal, double, float, int, uint, long, ulong, object, short or ushort

sbyte decimal, double, float, int, long, object or short


char decimal, double, float, int, uint, long, ulong, object or ushort
decimal object
double object
float double or object
int decimal, double, float, long or object
uint decimal, double, float, long, ulong, or object
long decimal, double, float or object
ulong decimal, double, float or object
object None
short decimal, double, float, int, long or object
ushort decimal, double, float, int, uint, long, ulong or object
string object
Fig. 6.5 Allowed im p lic it c o nve rsions.

 2002 Prentice Hall. All rights reserved.


12

6.7 C# Namespaces

• Namespace
– A group of classes and their methods
– FCL is composed of namespaces
– Namespaces are stored in .dll files called assemblies
– A list of the FLC namespaces are in Fig. 6.6
• .NET Framework, class library for info on all namespaces
– Included in a program with the using keyword

 2002 Prentice Hall. All rights reserved.


13

6.7 C# Namespaces

Na m esp a c e Desc rip tion


System Contains essential classes and data types (such as int,
double, char, etc.). Implicitly referenced by all C#
programs.
System.Data Contains classes that form ADO .NET, used for database
access and manipulation.
System.Drawing Contains classes used for drawing and graphics.
System.IO Contains classes for the input and output of data, such as with
files.
System.Threading Contains classes for multithreading, used to run multiple parts
of a program simultaneously.
System.Windows.Forms Contains classes used to create graphical user interfaces.
System.Xml Contains classes used to process XML data.
Fig. 6.6 Na mesp a c es in the Fra m ework Cla ss Lib ra ry.

 2002 Prentice Hall. All rights reserved.


14

6.8 Value Types and Reference Types

• Value types
– Contains data of the specified type
– Programmer created
• structs
• enumerations (Chapter 8)
• Reference types
– Contain an address to a spot in memory where the data is
– Programmer create
• Classes (Chapter 8)
• Interfaces (Chapter 8)
• Delegates (Chapter 9)
• All values are 32bit allowing cross-platform use
 2002 Prentice Hall. All rights reserved.
15
6.9 Passing Arguments: Call-By-Value vs.
Call-By-Reference
• Passing by value
– Send a method a copy of the object
– When returned are always returned by value
– Set by value by default
• Passing by reference
– Send a method the actual reference point
• Causes the variable to be changed throughout the program
– When returned are always returned by reference
– The ref keyword specifies by reference
– The out keyword means a called method will initialize it

 2002 Prentice Hall. All rights reserved.


16
1 // Fig. 6.8: RefOutTest.cs Outline
2 // Demonstrating ref and out parameters.
3
4 using System;
5 using System.Windows.Forms; RefOutTest.cs
6
7 class RefOutTest
8 { When passing a value by reference
9 // x is passed as a ref int (original value will change)
the value will be altered in the rest
10 static void SquareRef( ref int x )
11 { of the program as well
12 x = x * x;
13 }
14 Since the methods are void
15 // original value can
they do notbeneed
changed andvalue.
a return initialized
16 static void SquareOut( out int x )
17 {
18 x = 6; Since x is passed as out the variable
19 x = x * x;
20 } can then be initialed in the method
21
22 // x is passed by value (original value not changed)
23 static void Square( int x )
24 { Since not specified, this value is defaulted to being
25 x = x * x; passed by value. The value of x will not be changed
26 }
27
elsewhere in the program because a duplicate of the
28 static void Main( string[] args ) variable is created.
29 {
30 // create a new integer value, set it to 5
31 int y = 5;
32 int z; // declare z, but do not initialize it
33
 2002 Prentice Hall.
All rights reserved.
17
34 // display original values of y and z Outline
35 string output1 = "The value of y begins as "
36 + y + ", z begins uninitialized.\n\n\n";
37
38 // values of y and z are passed by value RefOutTest.cs
39 RefOutTest.SquareRef( ref y ); The calling of the SquareRef
40 RefOutTest.SquareOut( out z ); and SquareOut methods
41
42 // display values of y and z after modified by methods
43 // SquareRef and SquareOut
44 string output2 = "After calling SquareRef with y as an " +
45 "argument and SquareOut with z as an argument,\n" +
46 "the values of y and z are:\n\n" +
47 "y: " + y + "\nz: " + z + "\n\n\n";
48 The calling of the
49 // values of y and z are passed by value
SquareRef and SquareOut
50 RefOutTest.Square( y );
51 RefOutTest.Square( z ); methods by passing the
52 variables by value
53 // values of y and z will be same as before because Square
54 // did not modify variables directly
55 string output3 = "After calling Square on both x and y, " +
56 "the values of y and z are:\n\n" +
57 "y: " + y + "\nz: " + z + "\n\n";
58
59 MessageBox.Show( output1 + output2 + output3,
60 "Using ref and out Parameters", MessageBoxButtons.OK,
61 MessageBoxIcon.Information );
62
63 } // end method Main
64
65 } // end class RefOutTest

 2002 Prentice Hall.


All rights reserved.
18
Outline

RefOutTest.cs
Program Output

 2002 Prentice Hall.


All rights reserved.
19

6.12 Duration of Identifiers

• Duration
– The amount of time an identifier exist in memory
• Scope
– The section of a program in which the object can be
referenced
• Local variables
– Created when declared
– Destroyed when the block exits
– Not initialized
• Most variables are set to 0
• All bool variables are set to false
• All reference variables are set to null

 2002 Prentice Hall. All rights reserved.


20

6.13 Scope Rules

• Scope
– Portion of a program in which a variable can be accessed
– Class scope
• From when created in class
• Until end of class (})
• Global to all methods in that class
– Direct modification
• Repeated names causes previous to be hidden until scope ends
– Block scope
• From when created
• Until end of block (})
• Only used within that block
– Must be passed and modified indirectly
• Cannot repeat variable names

 2002 Prentice Hall. All rights reserved.


21
1 // Fig. 6.13: Scoping.cs Outline
2 // A Scoping example.
3
4 using System;
5 using System.Drawing; Scoping.cs
6 using System.Collections;
7 using System.ComponentModel;
8 using System.Windows.Forms;
9 using System.Data;
10
11 public class Scoping : System.Windows.Forms.Form
12 {
13 private System.ComponentModel.Container components = null;
14 private System.Windows.Forms.Label outputLabel;
15
16 public int x = 1; This variable has class scope and can
17 be used by any method in the class
18 public Scoping()
19 {
20 InitializeComponent();
21
22 int x = 5; This
// variable local to variable is
constructor local only to Scoping.
23 It hides the value of the global variable
24 outputLabel.Text = outputLabel.Text +
25 "local x in method Scoping is " + x;
Will output the value of 5
26
27 MethodA(); // MethodA has automatic local x;
28 MethodB(); // MethodB uses instance variable x
29 MethodA(); // MethodA creates new automatic local x
30 MethodB(); // instance variable x retains its value
31
32 outputLabel.Text = outputLabel.Text +
33 "\n\nlocal x in method Scoping is " + x;
Remains 5 despite changes
34 } to global version of x
 2002 Prentice Hall.
All rights reserved.
22
35 Outline
36 // Visual Studio .NET-generated code
37
38 public void MethodA()
39 { Scoping.cs
40 int x = 25; // initialized each timeUses
a isa called
new x variable that hides
41 the value of the global x
42 outputLabel.Text = outputLabel.Text +
43 "\n\nlocal x in MethodA is " + x +
44 " after entering MethodA";
45 ++x;
46 outputLabel.Text = outputLabel.Text +
47 "\nlocal x in MethodA is " + x +
48 " before exiting MethodA";
49 }
50
51 public void MethodB()
52 {
53 outputLabel.Text = outputLabel.Text +
54 "\n\ninstance variable x is " + x +
55 " on entering MethodB";
56 x *= 10; Uses the global version of x (1)
57 outputLabel.Text = outputLabel.Text +
58 "\ninstance varable x is " + x +
59 " on exiting MethodB";
Will permanently change
60 }
61 the value of x globally
62 // main entry point for application
63 [STAThread]
64 static void Main()
65 {
66 Application.Run( new Scoping() );
67 }
68
69 } // end of class Scoping
 2002 Prentice Hall.
All rights reserved.
23
Outline

Scoping.cs
Program Output

 2002 Prentice Hall.


All rights reserved.
24

6.17 Method Overloading

• Methods with the same name


– Can have the same name but need different arguments
• Variables passed must be different
– Either in type received or order sent
– Usually perform the same task
• On different data types

 2002 Prentice Hall. All rights reserved.


25
1 // Fig. 6.18: MethodOverload.cs Outline
2 // Using overloaded methods.
3
4 using System;
5 using System.Drawing; MethodOverload.cs
6 using System.Collections;
7 using System.ComponentModel;
8 using System.Windows.Forms;
9 using System.Data;
10
11 public class MethodOverload : System.Windows.Forms.Form
12 {
13 private System.ComponentModel.Container components = null;
14
15 private System.Windows.Forms.Label outputLabel;
16
17 public MethodOverload()
18 {
19 InitializeComponent();
20
21 // call both versions of Square
22 outputLabel.Text =
23 "The square of integer 7 is " + Square( 7 ) +
24 "\nThe square of double 7.5 is " + Square ( 7.5 ); Two versions of the square
25 } method are called
26
27 // Visual Studio .NET-generated code
28

 2002 Prentice Hall.


All rights reserved.
26
29 // first version, takes one integer Outline
30 public int Square ( int x )
31 { One method takes an
32 return x * x; int as parameters
33 } MethodOverload.cs
34
35 // second version, takes one double
36 public double Square ( double y )
37 {
38 return y * y;
39 } The other version of the method uses
40
41 [STAThread] a double instead of an integer
42 static void Main()
43 {
44 Application.Run( new MethodOverload() );
45 }
46
47 } // end of class MethodOverload

Program Output

 2002 Prentice Hall.


All rights reserved.
27
1 // Fig. 6.19: MethodOverload2.cs Outline
2 // Overloaded methods with identical signatures and
3 // different return types.
4
5 using System; MethodOverload2.cs
6
7 class MethodOverload2
8 {
9 public int Square( double x )
10 { This method returns an integer
11 return x * x;
12 }
13
14 // second Square method takes same number,
15 // order and type of arguments, error
16 public double Square( double y )
17 {
18 return y * y;
This method returns a double number
19 }
20
21 // main entry point for application
22 static void Main()
23 { Since the compiler cannot tell
24 int squareValue = 2; which method to use based on
25 Square( squareValue ); passed values an error is generated
26 }
27
28 } // end of class MethodOverload2

Program Output

 2002 Prentice Hall.


All rights reserved.

Potrebbero piacerti anche