52
Methods(1) Dr. Hakem Beitollahi Computer Engineering Department Soran University Lecture 5

Lecture 5

Embed Size (px)

DESCRIPTION

OOP with C# by Dr.hakim

Citation preview

  • 1. Methods(1)Lecture 5Dr. Hakem BeitollahiComputer Engineering DepartmentSoran University

2. Introduction Math Class Methods Methods Method Definitions Argument PromotionMethods(I) 2 3. Introdcution Most computer programs that solve real-worldproblems are much larger than programs thatyou have written yet! Experience has shown that the best way todevelop and maintain a large program is toconstruct it from small, simple pieces, ormodules. Methods are the building blocks of C# and theplace where all program activity occurs. Divide and conquer technique Construct a large program from small, simple pieces(e.g., components)Methods(I) 3 4. What are methods? Methods Called functions or procedures in other languages Allow programmers to modularize a program byseparating its tasks into self-contained unitso Statements in method bodies are written only once Reused from perhaps several locations in a program Hidden from other methods Avoid repeating codeo Enable the divide-and-conquer approacho Reusable in other programso User-defined or programmer-defined methodsMethods(I) 4 5. Software engineering tipTo promote software reusability, every methodshould be limited to performing a single, well-definedtask, and the name of the method shouldexpress that task effectively. Such methods makeprograms easier to write, test, debug andmaintain.A small method that performs one task is easierto test and debug than a larger method thatperforms many tasks.Methods(I) 5 6. Methods in C# C# programs are written by combining newmethods and classes available in the .NET Framework Class Library(FCL) The FCL provides: mathematical calculations, stringmanipulations, character manipulations,input/output operations and so on. A method is invoked by a method call.Methods(I) 6 7. Methods in C# Methods (Cont.) A method is invoked by a method callo Called method either returns a result or simply returns to thecallero method calls form hierarchical relationshipsMethods(I) 7 8. Math Class MethodsMethods(I) 8 9. Math Class Methods (I) Math class methods allow the programmer toperform certain common mathematicalcalculations. Methods are called by writing the name of themethod, followed by a left parenthesis, theargument and a right parenthesis. The parentheses may be empty, if we are callinga method that needs no information to performits task.Return a double value Example: double x = Math.Sqrt( 900.0 )Methods(I) 9Argument 10. Software Engineering Observation 6.3 It is not necessary to add an assemblyreference to use the Math class methodsin a program. Class Math is located innamespace System, which is availableto every program.Methods(I) 10 11. Math Class Methods (II)Methods(I) 11 12. Methods(I) 12 13. Math Class Methods (III)Methods(I) 13 14. Method DefinitionsMethods(I) 14 15. Method Definitions (I) The general form of a function isret-type method-name(parameter list){body of the function} The ret-type specifies the type of data that the methodreturns. A method may return any type of data except an array. The parameter list is a comma-separated list of variablenames and their associated types that receive the valuesof the arguments when the function is called. Methods must be declared within a class or astructure.Methods(I) 15 16. Method Definitions (II)Methods(I) 16 17. Method Definitions (III) A C# method consists of two parts The method header, and The method body The method header has the followingsyntax (()) The method body is simply a C# codeenclosed between { }Methods(I) 17 18. Method ExampleMethods(I) 18double computeTax(double income){double taxes ;if (income < 5000.0)return 0.0;taxes = 0.07 * (income-5000.0);return taxes;}Function headerFunction body 19. Method Definitions (IV) Basic characteristics of methods are: Return value typeo output: data type or void Method nameo Any legal character can be used in the name of a method.o method names begin with an uppercase letter.o The method names are verbs or verbs followed by adjectives or nouns. Method parameterso inputs for the methodo Empty parentheses indicate that the method requires no parameters. Parentheses Block of statementso The method block is surrounded with { } characters. Access levelo who can call the methodMethods(I) 19ExecuteFindIdSetNameGetNameCheckIfValidTestValidity 20. Method Signature The method signature is actually similar tothe method header except in two aspects: The parameters names may not be specifiedin the function signature The method signature must be ended by asemicolon Example UnnamedParameterSemicolon;double computeTaxes(double) ;double computeTaxes(double income) ;Methods(I) 20 21. Methods must be declared inside classInside class every method should bepublic or private (later)This method return nothing (void)Define an object for calling the methodMethods(I) 21Calling the method 22. Method Definitions (V) Each method must be defined inside a class or astruct. It must have a name. In our case the name isShowInfo. The keywords that precede the name of themethod are access specifier (public) and thereturn type (void). Parentheses follow the name of the method. They may contain parameters of the method. Our method does not take any parameters.Methods(I) 22 23. Method Definitions (VI)Methods(I) 23static void Main(){...}This is the Main() method. It is the entry point to each console or GUIapplication. It must be declared static.We will see later why. The return type for a Main() method may be void or int.The access specifier for the Main() method is omitted. In such a case a defaultone is used, which is private. 24. Method Definitions (VII) We create an instance of the Base class. We call the ShowInfo() method upon theobject. The method is called by specifying theobject instance, followed by the memberaccess operator the dot, followed by themethod name.Methods(I) 24Base bs = new Base();bs.ShowInfo(); 25. Another ExampleMethods(I) 25 26. Example: Tax computeA method to compute taxReturn type: doubleAn input parameter (argument) : doubleMethods(I) 26 27. Example: Tax computeA method to get salaryReturn type: doubleAn input parameter (argument) : stringMethods(I) 27 28. Example: Tax computeA method to print taxReturn type: voidAn input parameter (argument) : doubleMethods(I) 28 29. Example: Tax computeDefine an object from class: obob.NameofMethodCalling the methodsMethods(I) 29 30. More about Method parametersMethods(I) 30 31. Method Parameters A parameter is a value passed to themethod. Methods can take one or moreparameters. If methods work with data, we must passthe data to the methods. We do it by specifying them inside theparentheses. In the method definition, we must providea name and type for each parameter.Methods(I) 31 32. Example: Method parameters (I)Methods should be inside a classMethods(I) 32 33. Example: Method parameters (II)Method AddTwoValuesReturn type: intuse the return keyword to return avalueInput parameters: int a, int bMethods(I) 33 34. Example: Method parameters (III)Method AddThreeValuesReturn type: intuse the return keyword to return avalueInput parameters: int a, int b, int cMethods(I) 34 35. Example: Method parameters (IV)Define an object from class to callmethodsCalling methodsTwo methods return integer, so x andy should be integersMethods(I) 35 36. Methods inside the Main class (I) Another Example: define methods insidethe main classMethods(I) 36For methods inside the main classAccess specifier: should be static 37. Methods inside the Main class (II) Another Example: define methods insidethe main classNo need to define an object. Directlyuse the name of method to call themethodMethods(I) 37 38. Methods in Windows Application FormsMethods(I) 38 39. Methods(I) 39 40. Methods(I) 40 41. Common Programming Error 6.2 Defining a method outside the braces of aclass definition is a syntax error.Methods(I) 41 42. Common Programming Error 6.3 Omitting the return-value-type in a methoddefinition is a syntax error. If a methoddoes not return a value, the methodsreturn-value-type must be void.Methods(I) 42 43. Common Programming Error 6.4 Forgetting to return a value from a methodthat is supposed to return a value is asyntax error. If a return-value-type otherthan void is specified, the method mustcontain a return statement that returns avalue.Methods(I) 43 44. Common Programming Error 6.5 Returning a value from a method whosereturn type has been declared void is asyntax errorMethods(I) 44 45. Common Programming Error 6.6 Placing a semicolon after the rightparenthesis enclosing the parameter list ofa method definition is a syntax error.Methods(I) 45 46. Common Programming Error 6.7 Redefining a method parameter in themethods body is a syntax error.Methods(I) 46 47. Common Programming Error 6.9 Passing to a method an argument that isnot compatible with the correspondingparameters type is a syntax error.Methods(I) 47 48. Common Programming Error 6.9 Defining a method inside another methodis a syntax error (i.e., methods cannot benested)Methods(I) 48 49. Example: write a method to find maximumof three double values Use windows application formMethods(I) 49 50. Methods(I) 50 51. Methods(I) 51 52. Methods(I) 52