Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods. 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration.

Similar presentations


Presentation on theme: "Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods. 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration."— Presentation transcript:

1 Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods

2 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration. Math Class Methods Abstraction and Reuse The return Statement Objects Explicitly Creating Objects Creating and Accessing Objects Modifying Formal Arguments Call-By-Value Call- By-Reference

3 3 Introduction to Methods A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself. This is called structured programming. These parts are sometimes made into methods in C#. main() then uses these methods to solve the original problem.

4 4 Introduction to Methods Building Blocks of Programs Other terminology in other languages: Procedures, subprograms, functions In C#: methods I-P-O Input – Process – Output Basic subparts to any program Use methods for these ‘pieces’

5 5 Advantages of Methods Methods separate the concept (what is done) from the implementation (how it is done). Methods make programs easier to understand. Methods can be called several times in the same program, allowing the code to be reused.

6 6 Classes/Methods ( Predefined) C# Framework Class Library (FCL) defines many classes, e.g., Console MessageBox Int32 Math The definition of a class includes both methods and data properties: methods, e.g., Console.Write( ) Console.WriteLine( ) Int32.Parse( ) properties, e.g., Int32.MinValue Int32.MaxValue Math.PI Math.E

7 7 Methods A method should provide a well-defined, easy-to-understand functionality A method takes input (parameters), performs some actions, and (sometime) returns a value ( I-P-O) Example: invoking the WriteLine method of the Console class: Console.WriteLine ( "Whatever you are, be a good one.“ ); class methodInformation provided to the method (parameters) dot

8 8 Example: Math Class Methods

9 9 Programmer-Defined Class/Methods Write your own methods! Building blocks of programs Divide & Conquer Readability Re-use Your ‘definition’ can go in either: Same file as main() Separate file so others can use it, too

10 10 Components of Method Use 3 Pieces to using methods: Method Declaration Information for compiler To properly interpret calls Method Definition Actual implementation/code for what method does Method Call Transfer control to method

11 11 Methods Provide Abstraction and Reuse An abstraction hides (or ignores) the right details at the right time A method is abstract in that we don't really have to think about its internal details in order to use it e.g., we don't have to know how the WriteLine method works in order to invoke it Why abstraction? Divide and conquer Reuse Easier to understand

12 12 Method Declaration: Header A method declaration begins with a method header methodname returntype parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument class MyClass { static int SquareSum( int num1, int num2 ) … properties

13 13 Method Declaration: Body The method header is followed by the method body static int SquareSum(int num1, int num2) { int sum = num1 + num2; return sum * sum; } class MyClass { … … }

14 14 The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type The return statement specifies the value that will be returned Its expression must conform to the return type

15 15 Calling a Method Each time a method is called, the actual arguments in the invocation are copied into the formal arguments static int SquareSum (int num1, int num2) { int sum = num1 + num2; return sum * sum; } int num = SquareSum (2, 3);

16 16 More Examples of Classes/Methods The Console class Console The Write and WriteLine methods The String class String The Format method: e.g., String.Format( “ {0:C} ”, 2.0 )

17 17 More Examples of Classes/Methods The MessageBox classMessageBox The Show method we will use has four parameters text to be displayed, caption, buttons, icon Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog button. (Optional) Argument 2: Title bar string (Optional) Argument 1: Message to display

18 18 Sum.cs Program Output 1 // Sum.cs 2 // Summation with the for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Sum 8 { 9 static void Main( string[] args ) 10 { 11 int sum = 0; 12 13 for ( int number = 2; number <= 100; number += 2 ) 14 sum += number; 15 16 MessageBox.Show( "The sum is " + sum, 17 "Sum Even Integers from 2 to 100", 18 MessageBoxButtons.OK, 19 MessageBoxIcon.Information ); 20 21 } // end method Main 22 23 } // end class Sum Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog button. (Optional) Argument 2: Title bar string (Optional) Argument 1: Message to display Displays a message box with an OK button Has the message box contain an information icon The caption of the message boxThe title of the message box

19 19 MessageBox Buttons

20 20 MessageBox Icons

21 21 1 // Interest 2 // Calculating compound interest, using MessageBox and Pow. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Interest 8 { 9 static void Main( string[] args ) 10 { 11 decimal amount, principal = ( decimal ) 1000.00; 12 double rate =.05; 13 string output; 14 15 output = "Year\tAmount on deposit\n"; 16 17 for ( int year = 1; year <= 10; year++ ) 18 { 19 amount = principal * 20 ( decimal ) Math.Pow( 1.0 + rate, year ); 21 22 output += year + "\t" + 23 String.Format( "{0:C}", amount ) + "\n"; 24 } 25 26 MessageBox.Show( output, 27 "Compound Interest", 27 MessageBoxButtons.OK, 28 MessageBoxIcon.Information ); 28 29 } // end method Main 30 31 } // end class Interest Shows a message box that displays the output with a title of “Compound Interest” has an OK button and an information icon Loops through 10 times starting at 1 and ending at 10, adding 1 to the counter (year) each time Insert a TabFormats amount to have a currency formatting ($0.00)

22 22 Program Output

23 23 MaximumValue 1 // MaximumValue 2 // Finding the maximum of three doubles. 3 4 using System; 5 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: " ); 13 double number1 = Double.Parse( Console.ReadLine() ); 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 25 Console.WriteLine("\nmaximum is: " + max ); 26 27 } // end method Main The program gets three values from the user The three values are then passed to the Maximum method for use

24 24 Maximum Value Program Output 28 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 { 33 return Math.Max( x, Math.Max( y, z ) ); 34 35 } // end method Maximum 36 37 } // end class MaximumValue Enter first floating-point value: 37.3 Enter second floating-point value: 99.32 Enter third floating-point value: 27.1928 maximum is: 99.32 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.

25 25 Class Methods ( Static Methods) Previously we use class mainly to define related methods together: For example all math related methods are defined in the Math class The methods we have seen are defined as static (or class) methods To make a method static, a programmer applies the static modifier to the method definition The result of each invocation of a class (static) method is completely determined by the actual parameters

26 26 Brief About Static Modifier In C# Static modifier used with the class, field, method, properties, operator, event and constructors. We can not use static modifier with indexers, destructors. When we use static modifier with the members then they are no more part of instance of a class. Static members are a part of class itself. Therefore, there is exactly only one copy of each static field in a class. Note the following: 1.A constant is implicitly a static member. 2.A static member cannot be referenced through an instance. 3.You cannot use the this keyword with a static class member.

27 27 The Dual Roles of C# Classes Program modules: a list of (static) method declarations and (static) data fields To make a method static, a programmer applies the static modifier to the method definition The result of each invocation of a class method is completely determined by the actual parameters (and static fields of the class) To use a static method: ClassName.MethodName( … ); Blueprints for generating objects: Create an object Call methods of the object: objectName.MethodName( … );

28 Example: class Test { static int x = y; static int y = 5; static void Main() { Console.WriteLine(Test.x); Console.WriteLine(Test.y); Test.x = 99; Console.WriteLine(Test.x); } /* Output: 0 5 99 */ 28

29 29 Objects Object An object has internal state This is called encapsulation Thus the action (method) may depend on both parameters and internal state.

30 30 Creating and Accessing Objects We use the new operator to create an object Random myRandom; myRandom = new Random(); This calls the Random constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class To call a method on an object, we use the variable (not the class), e.g., Random generator1 = new Random(); int num = generate1.Next();

31 31 Example: the Random class Random Random () Random methods int Next () // returns an integer from 0 to Int32.MaxValue int Next (int max) // returns an integer from 0 upto but not including max int Next (int min, int max) // returns an integer from min upto but not including max double NextDouble ( ) // returns a double number from 0 to 1

32 The Rules for Accessing Static and Instance Members: class Test { int x; static int y; void F() { x = 1; // Ok y = 1; // Ok } static void G() { x = 1; // Error y = 1; // Ok } static void Main() { Test t = new Test(); t.x = 1; // Ok t.y = 1; // Error, cannot access static member through instance Test.x = 1; // Error, cannot access instance member through type Test.y = 1; // Ok } 32

33 33 Modifying Formal Arguments You can use the formal arguments (parameters) as variables inside the method Question: If a formal argument is modified inside a method, will the actual argument be changed? static int Square ( int x ) { x = x * x; return x; } static void Main ( string[] args ) { int x = 8; int y = Square( x ); Console.WriteLine ( x ); }

34 34 Parameter Passing If a modification on the formal argument has no effect on the actual argument, it is call by value If a modification on the formal argument can change the actual argument, it is call by reference

35 35 Call-By-Value and Call-By-Reference in C# Depend on the type of the formal argument For the simple data types, it is call-by- value Change to call-by-reference The ref keyword and the out keyword change a parameter to call-by-reference If a formal argument is modified in a method, the value is changed The ref or out keyword is required in both method declaration and method call ref requires that the parameter be initialized before enter a method while out requires that the parameter be set before return from a method

36 36 Example: ref static void Foo( int p ) {++p;} static void Main ( string[] args ) { int x = 8; Foo( x ); // a copy of x is made Console.WriteLine( x ); } static void Foo( ref int p ) {++p;} static void Main ( string[] args ) { int x = 8; Foo( ref x ); // x is ref Console.WriteLine( x ); }

37 37 Example: out static void Split( int timeLate, out int days, out int hours, out minutes ) { days = timeLate / 10000; hours = (timeLate / 100) % 100; minutes = timeLate % 100; } static void Main ( string[] args ) { int d, h, m; Split( 12345, out d, out h, out m ); Console.WriteLine( “{0}d {1}h {2}m”, d, h, m ); }

38 38 1 // RefOutTest.cs 2 // Demonstrating ref and out parameters. 3 4 using System; 5 using System.Windows.Forms; 6 7 class RefOutTest 8 { 9 // x is passed as a ref int (original value will change) 10 static void SquareRef( ref int x ) 11 { 12 x = x * x; 13 } 14 15 // original value can be changed and initialized 16 static void SquareOut( out int x ) 17 { 18 x = 6; 19 x = x * x; 20 } 21 22 // x is passed by value (original value not changed) 23 static void Square( int x ) 24 { 25 x = x * x; 26 } 27 28 static void Main( string[] args ) 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 When passing a value by reference the value will be altered in the rest of the program as well Since x is passed as out the variable can then be initialed in the method Since not specified, this value is defaulted to being passed by value. The value of x will not be changed elsewhere in the program because a duplicate of the variable is created. Since the methods are void they do not need a return value.

39 39 34 // display original values of y and z 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 39 RefOutTest.SquareRef( ref y ); 40 RefOutTest.SquareOut( out z ); 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 49 // values of y and z are passed by value 50 RefOutTest.Square( y ); 51 RefOutTest.Square( z ); 52 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 The calling of the SquareRef and SquareOut methods The calling of the SquareRef and SquareOut methods by passing the variables by value

40 40

41 41 Summary 1 A method should provide a well-defined, easy-to- understand functionality If a method is a static method Call the method by ClassName.MethodName( … ); If a method of a class is not a static method, then it is an instance method Create an object using the new operator Call methods of the object: objectVariableName.MethodName( … );

42 42 Summary 2 Parameter Passing Call-By-Value For the simple data types if a modification on the formal argument has no effect on the actual argument Call- By-Reference If a modification on the formal argument can change the actual argument The ref keyword and the out keyword change a parameter to call-by-reference


Download ppt "Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods. 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration."

Similar presentations


Ads by Google