COS240Lec31_CSMethods

Download Report

Transcript COS240Lec31_CSMethods

COS240 O-O Languages
AUBG, COS dept
Lecture 31
Title:
C# Methods
Reference: COS240 Syllabus
4/12/2017
Assoc. Prof. Stoyan Bonev
1
Lecture Contents:
• Structure of a C# program
– Accent on methods
• Components of a C# program
– Methods
– Types of parameters
•
•
•
•
By value and by reference (out, ref)
The params qualifier
Named parameters
Optional parameters
• Sample demo programs
4/12/2017
Assoc. Prof. Stoyan Bonev
2
Anatomy
of a C# program
The Basics of a C# Program
• C# program: collection of classes. Classes
capsulated as namespaces – named or
unnamed
• Namespace: collection of related classes
• Class: collection of data items and methods
• Method: designed to accomplish a specific task
• There is a main method in every C# program.
static void Main(string[] args)
• Main method provides the control of program
flow.
Java Programming: From Problem Analysis to Program
4 Design, 4e
4
From Problem Analysis
C# Elements
Figure 1-17 Relationship among C# elements
C#C#Programming:
Programming: From
From Problem Analysis to Program5Design
Problem Analysis to
5
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
C# Programming: From Problem Analysis to Program Design
6
/* SquareExample.cs
Author: Doyle */
using System;
namespace Square
{
public class SquareExample
{
Required method
public static void Main( )
{
int aValue = 768;
int result;
result = aValue * aValue;
Console.WriteLine(“{0} squared is {1}”, aValue, result);
Console.Read( );
}
}
}
C# Programming: From Problem Analysis to Program Design
7
Anatomy of a Method (continued)
Figure 3-1 Method components
C# Programming: From Problem Analysis to Program Design
8
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
C# Programming: From Problem Analysis to Program Design
9
Static Modifier
• Indicates member belongs to the type itself rather
than to a specific object of a class
• Main( ) must include static in heading
• Members of the Math class are static
– public static double Pow(double, double)
• Methods that use the static modifier are called
class methods
– Instance methods require an object
C# Programming: From Problem Analysis to Program Design
10
Access Modifiers
• public
• protected
• internal
• protected internal
• private
C# Programming: From Problem Analysis to Program Design
11
Level of Accessibility
C# Programming: From Problem Analysis to Program Design
12
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
C# Programming: From Problem Analysis to Program Design
13
Return
type
Return Type (continued)
public static double CalculateMilesPerGallon
(int milesTraveled, double gallonsUsed)
{
return milesTraveled / gallonsUsed;
}
Compatible value
(double) returned
C# Programming: From Problem Analysis to Program Design
14
Method Names
• Follow the rules for creating an identifier
– Pascal case style
– Action verb or prepositional phrase
• Examples
– CalculateSalesTax( )
– AssignSectionNumber( )
– DisplayResults( )
– InputAge( )
– ConvertInputValue( )
C# Programming: From Problem Analysis to Program Design
15
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
C# Programming: From Problem Analysis to Program Design
16
Parameters (continued)
public static double CalculateMilesPerGallon
(int milesTraveled, double gallonsUsed)
{
return milesTraveled / gallonsUsed;
Two formal
}
parameters
• Call to method inside Main( ) method
Console.WriteLine(“Miles per gallon = {0:N2}”,
CalculateMilesPerGallon(289, 12.2));
C# Programming: From Problem Analysis to Program Design
Actual
arguments
17
Parameters (continued)
• Like return types, parameters are optional
– Keyword void not required (inside parentheses) –
when there are no parameters
public void DisplayMessage( )
{
Console.Write(”This is “);
Console.Write(”an example of a method ”);
Console.WriteLine(“body. ”);
return; // no value is returned
}
C# Programming: From Problem Analysis to Program Design
18
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
C# Programming: From Problem Analysis to Program Design
19
Calling Class Methods
• Invoke 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
C# Programming: From Problem Analysis to Program Design
20
Predefined Methods
• Extensive class library
• Console class
– Overloaded methods
– Write( )
– WriteLine( )
– Read( )
• Not overloaded
• Returns an integer
C# Programming: From Problem Analysis to Program Design
21
Call Read( ) Methods
int aNumber;
Console.Write(“Enter a single character: ”);
aNumber = Console.Read( );
Console.WriteLine(“The value of the character entered: ”
+ aNumber);
Enter a single character: a
The value of the character entered: 97
C# Programming: From Problem Analysis to Program Design
22
Call Read( ) Methods (continued)
int aNumber;
Console.WriteLine(“The value of the character entered: “
+ (char) Console.Read( ));
Enter a single character: a
The value of the character entered: a
C# Programming: From Problem Analysis to Program Design
23
Call ReadLine( ) Methods
• More versatile than the Read( )
• Returns all characters up to the enter key
• Not overloaded
• Always returns a string
• String value must be parsed
C# Programming: From Problem Analysis to Program Design
24
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)
C# Programming: From Problem Analysis to Program Design
25
/* SquareInputValue.cs
Author: Doyle */
using System;
namespace Square
{
class SquareInputValue
{
static void Main( )
{
string inputStringValue;
double aValue, result;
Console.Write("Enter a value to be squared: ");
inputStringValue = Console.ReadLine( );
aValue = double.Parse(inputStringValue);
result = Math.Pow(aValue, 2);
Console.WriteLine("{0} squared is {1} ", aValue, result);
Console.ReadKey( );
}
} }
// Curly braces should be lined up
C# Programming: From Problem Analysis to Program Design
26
Call Parse( ) (continued)
string sValue = " true ";
Console.WriteLine (bool.Parse(sValue));
string strValue = "q";
Console.WriteLine(char.Parse(strValue));
C# Programming: From Problem Analysis to Program Design
// displays True
// displays q
27
Call Parse( ) with Incompatible
Value
• Console.WriteLine(char.Parse(sValue));
when sValue referenced “True”
Figure 3-6 System.FormatException run-time error
C# Programming: From Problem Analysis to Program Design
28
TryParse() method
• The TryParse( ) method will convert a
string value sent as an argument to its
equivalent numeric value, but it doesn’t
throw an exception when the conversion
fails.
Java Programming: From Problem Analysis to Program Design,
3e
29
TryParse( ) Method
• Parse( ) method and methods in Convert
class convert string values sent as arguments
to their equivalent numeric value
– If the string value being converted is invalid,
program crashes as an Exception is thrown. Two
ways to avoid the program crash:
• Could test the value prior to doing conversion with an
if statement
• Another option is to use the TryParse( ) method
C# Programming: From Problem Analysis to Program Design
30
TryParse( ) Method
public static bool TryParse
(string someStringValue, out int result)
String value
returned from
Console.ReadLine( )
Result stored
here, when
conversion occurs
Test…if problem,
prints message, does
not try to convert
if (int.TryParse(inValue, out v1) = = false)
Console.WriteLine("Did not input a valid integer - " +
"0 stored in v1");
C# Programming: From Problem Analysis to Program Design
31
TryParse( ) Method
• Each of the built in data types have a
TryParse( ) method
– char.TryParse( ), int.TryParse( ),
decimal.TryParse( ), etc
• If there is a problem with the data, 0 is
stored in the out argument and TryParse( )
returns false.
Show LargestValue example
C# Programming: From Problem Analysis to Program Design
32
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);
C# Programming: From Problem Analysis to Program Design
33
Predefined methods
C# Programming: From Problem Analysis to Program Design
34
C# Programming: From Problem Analysis to Program Design
35
C# Programming: From Problem Analysis to Program Design
36
C# Programming: From Problem Analysis to Program Design
37
Math( ) Class
Each call
double aValue = 78.926;
returns a value
double result1,
result2;
result1 = Math.Floor(aValue);
// result1 = 78
result2 = Math.Sqrt(aValue);
// result2 = 8.88403061678651
Console.Write(“aValue rounded to 2 decimal places”
+ “ is {0}”, Math.Round(aValue, 2));
aValue rounded to 2
decimal places is 78.93
C# Programming: From Problem Analysis to Program Design
38
Method Calls That Return Values
Line 1 int aValue = 200;
In an assignment
statement
Line 2 int bValue = 896;
Line 3 int result;
Line 4 result = Math.Max(aValue, bValue); // result = 896
Part of arithmetic expression
Line 5 result += bValue *
Line 6
Math.Max(aValue, bValue) – aValue;
// result = 896 + (896 * 896 - 200)
(result = 803512)
Line 7 Console.WriteLine(“Largest value between {0} ”
Line 8
+ “and {1} is {2}”, aValue, bValue,
Line 9
Math.Max(aValue, bValue));
Argument to
another method call
C# Programming: From Problem Analysis to Program Design
39
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
C# Programming: From Problem Analysis to Program Design
40
class
method
Writing Your Own Class
Methods – void Types
A call to this method
public static void DisplayInstructions( )
looks like:
{
DisplayInstructions( );
Console.WriteLine(“This program will determine how ”
+ “much carpet to purchase.”);
Console.WriteLine( );
Console.WriteLine(“You will be asked to enter the ”
+ “ size of the room and ”);
Console.WriteLine(“the price of the carpet, ”
+ ”in price per square yards.”);
Console.WriteLine( );
}
C# Programming: From Problem Analysis to Program Design
41
Writing Your Own Class
Methods – void Types (continued)
public static void DisplayResults(double squareYards,
double pricePerSquareYard)
{
Console.Write(“Total Square Yards needed: ”);
Console.WriteLine(“{0:N2}”, squareYards);
Console.Write(“Total Cost at {0:C} “, pricePerSquareYard);
Console.WriteLine(“ per Square Yard: {0:C}”,
(squareYards * pricePerSquareYard));
}
• static method called from within the class where it resides
• To invoke method – DisplayResults(16.5, 18.95);
C# Programming: From Problem Analysis to Program Design
42
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
C# Programming: From Problem Analysis to Program Design
43
Value-Returning Method (continued)
public static double GetLength( )
{
Return type→
string inputValue;
double
int feet, inches;
Console.Write(“Enter the Length in feet: ”);
inputValue = Console.ReadLine( );
feet =
int.Parse(inputValue);
Console.Write(“Enter the Length in inches: “);
inputValue = Console.ReadLine( );
inches = int.Parse(inputValue);
double
return (feet + (double) inches / 12);
returned
}
C# Programming: From Problem Analysis to Program Design
44
Types of Parameters
• C# offers both
– Call by value parameters (default type)
– Call by reference parameters
C# Programming: From Problem Analysis to Program Design
45
Variables can hold either value types or reference types
Value type
- where a variable X contains a value type, it directly
contains an entity with some value. No other variable Y
can directly contain the object contained by X
(although Y might contain an entity with the same
value).
Reference type
- where a variable X contains a reference type, what it
directly contains is something that refers to an object.
Another variable Y can contain a reference to the same
object referred to by X.
Reference types actually hold the value of a memory
address
object
they
4/12/2017 occupied by the
Assoc.
Prof. Stoyan
Bonev reference.
46
4/12/2017
Assoc. Prof. Stoyan Bonev
47
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. Useful
when there is need to return more than one value
C# Programming: From Problem Analysis to Program Design
48
Types of Parameters
• When you use ref/out, call by reference is
assumed.
• You must include ref/out both in the call
(actual argument) and in the method heading
(formal parameter). They must match.
• The ref keyword cannot be used unless the
original argument is initialized before it is sent to
the method.
• This restriction does not exist for out.
C# Programming: From Problem Analysis to Program Design
49
Types of Parameters
Demo program Methods1.cs
C# Programming: From Problem Analysis to Program Design
50
Types of Parameters
Demo program parameters.cs
C# Programming: From Problem Analysis to Program Design
51
Types of Parameters (continued)
Figure 3-9 Call by reference versus value
C# Programming: From Problem Analysis to Program Design
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
C# Programming: From Problem Analysis to Program Design
53
Parameters Example
// Code pulled from Parameters.cs solutions
int testValue = 1;
TestDefault(testValue);
Console.WriteLine("Upon return from TestDefault "
+ "Value: {0}", testValue);
Console.WriteLine( );
Upon return from
TestDefault
Value: 1
public static void TestDefault(int aValue)
{
aValue = 111;
Console.WriteLine("In TestDefault - Value: {0}", aValue);
}
C# Programming: From Problem Analysis to Program Design
54
Parameters Example (continued)
// Code pulled from Parameters.cs solutions
int testValue = 1;
TestRef(ref testValue);
Console.WriteLine("Upon return from TestRef "
+ "Value: {0}", testValue);
Console.WriteLine( );
Upon return from
TestRef
Value: 333
public static void TestRef (ref int aValue)
{
aValue = 333;
Console.WriteLine("In TestRef - Value: {0}", aValue);
}
C# Programming: From Problem Analysis to Program Design
55
Parameters Example (continued)
// Code pulled from Parameters.cs solutions
int testValue2;
TestOut(out testValue2);
Console.WriteLine("Upon return from TestOut "
+ "Value: {0}", testValue2);
Console.WriteLine( );
Upon return from
TestOut
public static void TestOut (out int aValue)
Value: 222
{
aValue = 222;
Console.WriteLine("In TestOut - Value: {0}", aValue);
}
C# Programming: From Problem Analysis to Program Design
56
Parameters.cs
Figure 3-8 Output from ParameterClass example
C# Programming: From Problem Analysis to Program Design
57
Types of Parameters (continued)
Figure 3-9 Call by reference versus value
C# Programming: From Problem Analysis to Program Design
58
Testing Parameters App
• Comment/uncomment sections while testing
Figure 3-10 Visual Studio comment out icon
C# Programming: From Problem Analysis to Program Design
59
Demo Programs and Exercises
Java Programming: From Problem Analysis to Program Design,
3e
60
Demo Programs and Exercises
• Write a method with two integer parameters
and no return value which swaps/exchanges/
the values of its parameters.
• Test the method with value parameters
• Test the method with ref parameters
• Test the method with out parameters
Java Programming: From Problem Analysis to Program Design,
3e
61
Demo Programs
// PP parameter passing mechanisms - swap by value
public static void swapByVal(int pa, int pb)
{
int temp;
temp = pa; pa = pb; pb = temp;
}
//===================================
// Test PP parameter passing mechanisms by value
int a, b;
a = 20; b = 50;
Console.WriteLine("Before swapByVal a={0}, b={1}", a, b);
swapByVal(a, b);
Console.WriteLine(" After swapByVal a={0}, b={1}", a, b);
Java Programming: From Problem Analysis to Program Design,
3e
62
Demo Programs
// PP parameter passing mechanisms - swap by ref
public static void swapByRef1(ref int pa, ref int pb)
{
int temp;
temp = pa; pa = pb; pb = temp;
}
//============================================
// Test PP parameter passing mechanisms by ref
int a, b; a = 70; b = 90;
Console.WriteLine("Before swapByRef1 a={0}, b={1}", a, b);
swapByRef1(ref a, ref b);
Console.WriteLine(" After swapByRef1 a={0}, b={1}", a, b);
Java Programming: From Problem Analysis to Program Design,
3e
63
Demo Programs
// PP parameter passing mechanisms - swap by out
public static void swapByRef2(out int pa, out int pb)
{
pa = 230;
pb = 250;
}
//================================
// Test PP parameter passing mechanisms by out
int c, d; // both vars not initialized
Console.WriteLine("Before swapByRef2 c={0}, d={1}", c, d);
swapByRef2(out c, out d);
Console.WriteLine(" After swapByRef2 c={0}, d={1}", c, d);
Java Programming: From Problem Analysis to Program Design,
3e
64
Params Parameter
• Keyword params used
– Appears in formal parameter list (heading to the
method)
– Must be last parameter listed in the method heading
• Indicates number of arguments to the method that
may vary
C# Programming: From Problem Analysis to Program Design
65
Params Parameters
• When a method uses the params modifier, the
parameter is considered a parameter array. It is used
to indicate that the number of arguments to the
method may vary.
• The params argument appears in method heading
only. It is prefix of a formal parameter – array
identifier and must be the last parameter listed.
• That formal parameter cannot be defined as ref or
as out parameter.
• Demo program VaryingArguments.cs
C# Programming: From Problem Analysis to Program Design
66
Types of Parameters
Demo program
VaryingArguments.cs
C# Programming: From Problem Analysis to Program Design
67
Params Parameters
using System;
namespace VaryingArguments
{
class VaryingArguments
{
public static void Main()
{
DisplayItems(1, 2, 3, 5);
int[] anArray = new int[5] {100, 200, 300, 400, 500};
DisplayItems(anArray);
DisplayItems(1500, anArray[1] * anArray [2]);
}
public static void DisplayItems(params int[] item)
{
for ( int i = 0 ; i < item.Length ; i++ ) { Console.Write(item[i] + "\t"); }
Console.WriteLine();
}
} // end From
of class
C# Programming:
Problem Analysis to Program Design
68
} // end of namespace
Params Parameters
Demo program VaryingArguments.cs
• A method may be called with a single value.
• Another call to the same method may send 4, or
10, or 100 values, or an array of values
• A variable number of arguments are accepted
when params argument is included.
• Makes method very flexible.
C# Programming: From Problem Analysis to Program Design
69
Demo Programs
Evolution of the routine concept
applied to C# methods
70
Method Evolution
• Overloaded methods
Java Programming: From Problem Analysis to Program Design,
3e
71
Method Evolution
public static void displaystr()
{
for(int i=1; i<=1; i++) { Console.WriteLine("Bulgaria"); }
Console.WriteLine("\n");
}
Java Programming: From Problem Analysis to Program Design,
3e
72
Method Evolution
public static void displaystr(int pn)
{
for(int i=1; i<=pn; i++) { Console.WriteLine("Bulgaria"); }
Console.WriteLine("\n");
}
Java Programming: From Problem Analysis to Program Design,
3e
73
Method Evolution
public static void displaystr(String ps)
{
for(int i=1; i<=1; i++) { Console.WriteLine(ps); }
Console.WriteLine("\n");
}
Java Programming: From Problem Analysis to Program Design,
3e
74
Method Evolution
public static void displaystr(String ps, int pn)
{
for(int i=1; i<=pn; i++) { Console.WriteLine(ps); }
Console.WriteLine("\n");
}
Java Programming: From Problem Analysis to Program Design,
3e
75
Method Evolution
public static void displaystr()
{
for(int i=1; i<=1; i++) { Console.WriteLine("Bulgaria"); }
}
//========================================================
public static void displaystr(String ps)
{
for(int i=1; i<=1; i++) { Console.WriteLine(ps); }
}
//========================================================
public static void displaystr(int pn)
{
for(int i=1; i<=pn; i++) { Console.WriteLine("Bulgaria"); }
}
//========================================================
public static void displaystr(String ps, int pn)
{
for(int i=1; i<=pn; i++) { Console.WriteLine(ps); }
}
Java Programming: From Problem Analysis to Program Design,
3e
76
Method Evolution
• Overloaded methods
// Test PP overloaded methods
displaystr();
displaystr("Germany");
displaystr(2);
displaystr("United Kingdom", 4);
Java Programming: From Problem Analysis to Program Design,
3e
77
Method Evolution
• Default arguments methods
Java Programming: From Problem Analysis to Program Design,
3e
78
Method Evolution
• Default arguments methods
//
// PP default arguments methods
public static double
aveVal(int pa=10, int pb=20, int pc=30, int pd=40)
{
return ( pa + pb + pc + pd ) / 4.0;
}
Java Programming: From Problem Analysis to Program Design,
3e
79
Method Evolution
• Default arguments methods
//
// Test PP default arguments functions
Console.WriteLine("\n {0}", aveVal());
Console.WriteLine("\n {0}", aveVal(100));
Console.WriteLine("\n {0}", aveVal(100, 200));
Console.WriteLine("\n {0}", aveVal(100, 200, 300));
Console.WriteLine("\n {0}", aveVal(100, 200, 300, 400));
Java Programming: From Problem Analysis to Program Design,
3e
80
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 parameters
C# Programming: From Problem Analysis to Program Design
81
Method Evolution
• Named parameters
Java Programming: From Problem Analysis to Program Design,
3e
82
Named Parameters
• Named arguments free you from the need to
remember or to look up the order of parameters for
the method call
DoSomething (name: “Robert Wiser", age: 20);
DoSomething (name: "Paul Nelson", major: “IS");
DoSomething (name: “Fred Terrell", age: 25, major: “BUS");
C# Programming: From Problem Analysis to Program Design
83
Method Evolution
• An artefact with C# methods
Java Programming: From Problem Analysis to Program Design,
3e
84
Method Evolution
•
•
•
•
An artefact with C# methods
Given a method
int add(int pa, int pb)
{
return pa + pb;
}
Java Programming: From Problem Analysis to Program Design,
3e
85
Method Evolution
• An artefact with C# methods
• Are the call statements valid?
int a = 20, b = 50;
int x = add(5, 6);
int y = add(a, b);;
Int z = add(a + 5 * 6, b – 7 * 8);
Int t = add(a = 5 * 6, b = 7 * 8);
Java Programming: From Problem Analysis to Program Design,
3e
86
Practical session
Expand the program Methods1.cs adding more
methods that reside in the same class with method
Main():
• Iterative GCD – gcdi()
• Iterative/Recursive factorial – facti(), factr()
• Iterative/Recursive Fibonacci – fiboi(), fibor()
• Iterative/Recursive Sum(1..n) – sumi(), sumr()
• Iterative/Recursive Power operator simulator –
powi(), powr()
C# Programming: From Problem Analysis to Program Design
87
Practical session
Expand the program Parameters.cs adding more
methods that reside in the same class with method
Main():
• Method void swap(int pa, int pb) that exchanges
the values of its parameters/arguments
• Test the swap method with:
– Input parameters by value
– Output ref parameters
– Output out parameters
C# Programming: From Problem Analysis to Program Design
88
Thank You
for
Your attention!