csci 3328 object oriented programming in c# chapter 6: methods 1 xiang lian the university of texas...

22
CSCI 3328 Object CSCI 3328 Object Oriented Programming Oriented Programming in C# in C# Chapter 6: Methods Chapter 6: Methods 1 Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 [email protected]

Upload: kelly-waters

Post on 02-Jan-2016

230 views

Category:

Documents


1 download

TRANSCRIPT

CSCI 3328 Object Oriented CSCI 3328 Object Oriented Programming in C# Programming in C# Chapter 6: MethodsChapter 6: Methods

1

Xiang Lian

The University of Texas – Pan American

Edinburg, TX 78539

[email protected]

Common Ways of Packaging Code

• Properties

• Methods

• Classes

• Namespaces (related classes are grouped into a namespace)

• Prepackaged codes are available in .Net framework class library

2

Class Math

• From namespace System• Provides a collection of methods for mathematics

–Sqrt(x)• Console.WriteLine(Math.Sqrt(900.0))

–Abs(x)–Ceiling(x)

• Rounds x to the smallest integer, greater than x.• Int32 numofGalons = Convert.ToInt16(Math.Ceiling(totalSqFt/450));

–Floor(x) • Rounds x to the largest integer, less than or equal to x.

–Pow(x,y) • x raised to the power of y

3

Accessing Static Methods of a Class

• Syntax– ClassName.MethodName(arguments)– Dot . is a member access operator

• Access a method–Math.Cos(x)–Math.Exp(x) (i.e., ex)

• Access constants–Math.PI (i.e., 3.1415926…)–Math.E (i.e., 2.718281828…)

4

Example of Floor and Ceiling

• Floor: – Math.Floor(2.10) = 2 – Math.Floor(2.00) = 2 – Math.Floor(1.90) = 1 – Math.Floor(1.80) = 1

• Ceiling: – Math.Ceiling(0.00) = 0 – Math.Ceiling(0.10) = 1 – Math.Ceiling(0.20) = 1 – Math.Ceiling(0.30) = 1

5

Main Declared as Static

• Why must Main be declared static?– It is the applications entry point

– Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class• public static void Main (string args[])

• The args allows one to call the application and pass parameters in from the command line

6

Declaring Methods with Multiple Parameters

• Parameters are specified as a comma-separated list– Actual parameters appear in the call – Formal parameters appear in the method declaration

• Both actual and formal parameters must have exactly same number of parameters

• Both actual and formal parameters must agree in their types

• Values are assigned according to the order of appearance rather than variable names

7

Method Declaration and Call

• Method declarationpublic double Maximum(double x, double y, double z)

{

// code here

return maximumValue;

}

• Method call–double result = Maximum (num1, num2, num3);

8

Method-Call Stack and Activation Records• When an application calls a method the return address of the

calling method is pushed on to the program-execution stack (method-call stack)

• If series of methods are called, successive return addresses are pushed onto the stack (LIFO)

• The program-execution stack also contains the memory for the local variables used in each invocation of a method during the application’s execution– This is known as the activation record (stack frame) of the method call

• When the method completes and return to its caller, the activation record for this method call is popped off the stack, and those local variables are no longer known to the application

• If more methods calls occur than available memory for program-execution stack, stack overflow error occurs

9

Illustration of Method-Call Stack

• Stackpublic double Maximum(double x, double y, double z)

{

// …

}

public static void Main (string [] args)

{

double a, b, c;

// …

Maximum(a, b, c);

}

10

aMain()

stack

bcxyz

Maximum()

Argument Promotion and Casting• Math.Sqrt(4)– Expects a double argument– However, accepts an integer and promotes it to a

double and returns the result of 2.0

• When a method expects an integer– if you pass a real number, you get an error, since

the method cannot truncate numbers arbitrarily– float can be promoted to double, but double cannot

be converted into float implicitly

• If you want to go the other way, you have to cast it

11

The .Net Framework Library

• Some examples– System.Windows.Forms

– System.Windows.Controls (for WPFs)

– System.Linq (for language integrated query)

– System.IO (for files, keyboards, monitors, etc.)

– System.Web (creating web applications)

– System.Text (manipulate characters and strings)

12

Random Number Generation• Needed for your card game assignment coming up later.

• Objects of class Random can produce random byte, int and double values.– Random randomNumbers = new Random();

– int randomValue = randomNumbers.Next();• Generates random values in the range 0 to +2,147,483,646

• This uses the current time as seed value to generate a psuedorandom number

• If you place number .Next(1,53), it will generate a random value 1 to 52

– Random randomNumbers = new Random(seedvalue);• You can use a seed value when creating a Random object

• This can lead to a repeating exact same sequence

13

Random Number Generation (cont'd)

• Random randomNumbers = new Random();– randomNumbers.Next();• [0, +2,147,483,646]

– randomNumbers.Next(6);• [0, 6)

• i.e., 0, 1, 2, 3, 4, 5

– randomNumbers.Next(1, 7);• [1, 7)

• i.e., 1, 2, 3, 4, 5, 6

14

Example of Rolling a Die

Random randomNumbers = new Random();int face;for (int counter = 1; counter <= 20; counter++){

face = randomNumbers.Next(1, 7);Console.Write("{0} ", face);if ( counter%5 == 0)

Console.WriteLine();}

15

Method Overloading

• Methods of the same name can be declared in the same class, as long as they have different set of parameters(number, type and order).

• Examples:public int Square (int intValue)

{

return intValue*intValue;

}

public double Square (double doubleValue)

{

return doubleValue*doubleValue;

}

16

Distinguishing Between Overloaded Methods

• Distinguish between overloaded methods by signature–Method's name– The number of parameters– Types of parameters– Order of parameters– Parameter passing methods

• Return data types cannot distinguish overloaded methods

17

Recursion

• Method that calls itself

• A recursive method solves only a simple problem (base case)

• For any thing other than the base case, it calls itself with a slightly simpler problem– Eventually it becomes the base case for which it

knows the answer

18

Example of Factorial

// n!public static long Factorial (long number){

// base caseif (number <= 1)

return 1;else

return number * Factorial(number -1);}

19

Passing Arguments: Value and Reference

• Applying the ref keyword to a parameter declaration allows you pass a variable to a method by reference– The method now will be able to modify the

original variable– The original variable must be initialized before

passing to the method

• If you do not want to initialize the variable, you can use the modifier: out– This means that the called method will assign a

value to the original variable– If not, a compiler error will result

20

Example of Parameter Passing

void SquareRef(ref int x)

{

x = x*x; // modify caller's variable;

// x must be initialized

}

void SquareOut(out int x)

{

x = 6; // x does not need to be initialized

x = x*x;

}

int Square (int x)

{

x=x*x; // local variable x within method

return x;

}

21

// call methods

int y= 5, z;

SquareRef(ref y);

SquareOut(out z);

Square(y);

Square(z);

22