SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Methods(1) 
Lecture 5 
Dr. Hakem Beitollahi 
Computer Engineering Department 
Soran University
 Introduction 
 Math Class Methods 
 Methods 
 Method Definitions 
 Argument Promotion 
Methods(I)— 2
Introdcution 
 Most computer programs that solve real-world 
problems are much larger than programs that 
you have written yet! 
 Experience has shown that the best way to 
develop and maintain a large program is to 
construct it from small, simple pieces, or 
modules. 
 Methods are the building blocks of C# and the 
place where all program activity occurs. 
 Divide and conquer technique 
 Construct a large program from small, simple pieces 
(e.g., components) 
Methods(I)— 3
What are methods? 
 Methods 
 Called functions or procedures in other languages 
 Allow programmers to modularize a program by 
separating its tasks into self-contained units 
o Statements in method bodies are written only once 
 Reused from perhaps several locations in a program 
 Hidden from other methods 
 Avoid repeating code 
o Enable the divide-and-conquer approach 
o Reusable in other programs 
o User-defined or programmer-defined methods 
Methods(I)— 4
Software engineering tip 
To promote software reusability, every method 
should be limited to performing a single, well-defined 
task, and the name of the method should 
express that task effectively. Such methods make 
programs easier to write, test, debug and 
maintain. 
A small method that performs one task is easier 
to test and debug than a larger method that 
performs many tasks. 
Methods(I)— 5
Methods in C# 
 C# programs are written by combining new 
methods and classes 
 available in the .NET Framework Class Library 
(FCL) 
 The FCL provides: 
 mathematical calculations, string 
manipulations, character manipulations, 
input/output operations and so on. 
 A method is invoked by a method call. 
Methods(I)— 6
Methods in C# 
 Methods (Cont.) 
 A method is invoked by a method call 
o Called method either returns a result or simply returns to the 
caller 
o method calls form hierarchical relationships 
Methods(I)— 7
Math Class Methods 
Methods(I)— 8
Math Class Methods (I) 
 Math class methods allow the programmer to 
perform certain common mathematical 
calculations. 
 Methods are called by writing the name of the 
method, followed by a left parenthesis, the 
argument and a right parenthesis. 
 The parentheses may be empty, if we are calling 
a method that needs no information to perform 
its task. 
Return a double value 
 Example: 
 double x = Math.Sqrt( 900.0 ) 
Methods(I)— 9 
Argument
Software Engineering Observation 6.3 
 It is not necessary to add an assembly 
reference to use the Math class methods 
in a program. Class Math is located in 
namespace System, which is available 
to every program. 
Methods(I)— 10
Math Class Methods (II) 
Methods(I)— 11
Methods(I)— 12
Math Class Methods (III) 
Methods(I)— 13
Method Definitions 
Methods(I)— 14
Method Definitions (I) 
 The general form of a function is 
ret-type method-name(parameter list) 
{ 
body of the function 
} 
 The ret-type specifies the type of data that the method 
returns. 
 A method may return any type of data except an array. 
 The parameter list is a comma-separated list of variable 
names and their associated types that receive the values 
of the arguments when the function is called. 
 Methods must be declared within a class or a 
structure. 
Methods(I)— 15
Method Definitions (II) 
Methods(I)— 16
Method Definitions (III) 
 A C# method consists of two parts 
 The method header, and 
 The method body 
 The method header has the following 
syntax 
<<rreettuurrnn vvaalluuee>> <<nnaammee>> ((<<ppaarraammeetteerr lliisstt>>)) 
 The method body is simply a C# code 
enclosed between { } 
Methods(I)— 17
Method Example 
Methods(I)— 18 
double computeTax(double income) 
{ 
double taxes ; 
if (income < 5000.0) 
return 0.0; 
taxes = 0.07 * (income-5000.0); 
return taxes; 
} 
Function header 
Function body
Method Definitions (IV) 
 Basic characteristics of methods are: 
 Return value type 
o output: data type or void 
 Method name 
o 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 parameters 
o inputs for the method 
o Empty parentheses indicate that the method requires no parameters. 
 Parentheses 
 Block of statements 
o The method block is surrounded with { } characters. 
 Access level 
o who can call the method 
Methods(I)— 19 
Execute 
FindId 
SetName 
GetName 
CheckIfValid 
TestValidity
Method Signature 
 The method signature is actually similar to 
the method header except in two aspects: 
 The parameters’ names may not be specified 
in the function signature 
 The method signature must be ended by a 
semicolon 
 Example Unnamed 
Parameter 
Semicolon 
; 
double computeTaxes(double) ; 
double computeTaxes(double income) ; 
Methods(I)— 20
Methods must be declared inside class 
Inside class every method should be 
public or private (later) 
This method return nothing (void) 
Define an object for calling the method 
Methods(I)— 21 
Calling the method
Method Definitions (V) 
 Each method must be defined inside a class or a 
struct. 
 It must have a name. In our case the name is 
ShowInfo. 
 The keywords that precede the name of the 
method are access specifier (public) and the 
return 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
Method Definitions (VI) 
Methods(I)— 23 
static void Main() 
{ 
... 
} 
This is the Main() method. It is the entry point to each console or GUI 
application. 
 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 default 
one is used, which is private.
Method Definitions (VII) 
 We create an instance of the Base class. 
 We call the ShowInfo() method upon the 
object. 
 The method is called by specifying the 
object instance, followed by the member 
access operator — the dot, followed by the 
method name. 
Methods(I)— 24 
Base bs = new Base(); 
bs.ShowInfo();
Another Example 
Methods(I)— 25
Example: Tax compute 
A method to compute tax 
Return type: double 
An input parameter (argument) : double 
Methods(I)— 26
Example: Tax compute 
A method to get salary 
Return type: double 
An input parameter (argument) : string 
Methods(I)— 27
Example: Tax compute 
A method to print tax 
Return type: void 
An input parameter (argument) : double 
Methods(I)— 28
Example: Tax compute 
Define an object from class: ob 
ob.NameofMethod 
Calling the methods 
Methods(I)— 29
More about Method parameters 
Methods(I)— 30
Method Parameters 
 A parameter is a value passed to the 
method. 
 Methods can take one or more 
parameters. 
 If methods work with data, we must pass 
the data to the methods. 
 We do it by specifying them inside the 
parentheses. 
 In the method definition, we must provide 
a name and type for each parameter. 
Methods(I)— 31
Example: Method parameters (I) 
Methods should be inside a class 
Methods(I)— 32
Example: Method parameters (II) 
Method AddTwoValues 
Return type: int 
use the return keyword to return a 
value 
Input parameters: int a, int b 
Methods(I)— 33
Example: Method parameters (III) 
Method AddThreeValues 
Return type: int 
use the return keyword to return a 
value 
Input parameters: int a, int b, int c 
Methods(I)— 34
Example: Method parameters (IV) 
Define an object from class to call 
methods 
Calling methods 
Two methods return integer, so x and 
y should be integers 
Methods(I)— 35
Methods inside the Main class (I) 
 Another Example: define methods inside 
the main class 
Methods(I)— 36 
For methods inside the main class 
Access specifier: should be static
Methods inside the Main class (II) 
 Another Example: define methods inside 
the main class 
No need to define an object. Directly 
use the name of method to call the 
method 
Methods(I)— 37
Methods in Windows Application Forms 
Methods(I)— 38
Methods(I)— 39
Methods(I)— 40
Common Programming Error 6.2 
 Defining a method outside the braces of a 
class definition is a syntax error. 
Methods(I)— 41
Common Programming Error 6.3 
 Omitting the return-value-type in a method 
definition is a syntax error. If a method 
does not return a value, the method’s 
return-value-type must be void. 
Methods(I)— 42
Common Programming Error 6.4 
 Forgetting to return a value from a method 
that is supposed to return a value is a 
syntax error. If a return-value-type other 
than void is specified, the method must 
contain a return statement that returns a 
value. 
Methods(I)— 43
Common Programming Error 6.5 
 Returning a value from a method whose 
return type has been declared void is a 
syntax error 
Methods(I)— 44
Common Programming Error 6.6 
 Placing a semicolon after the right 
parenthesis enclosing the parameter list of 
a method definition is a syntax error. 
Methods(I)— 45
Common Programming Error 6.7 
 Redefining a method parameter in the 
method’s body is a syntax error. 
Methods(I)— 46
Common Programming Error 6.9 
 Passing to a method an argument that is 
not compatible with the corresponding 
parameter’s type is a syntax error. 
Methods(I)— 47
Common Programming Error 6.9 
 Defining a method inside another method 
is a syntax error (i.e., methods cannot be 
nested) 
Methods(I)— 48
 Example: write a method to find maximum 
of three double values 
 Use windows application form 
Methods(I)— 49
Methods(I)— 50
Methods(I)— 51
Methods(I)— 52

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Csc153 chapter 02
Csc153 chapter 02Csc153 chapter 02
Csc153 chapter 02
 
Csc153 chapter 01
Csc153 chapter 01Csc153 chapter 01
Csc153 chapter 01
 
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMINGFINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
FINAL PAPER FP301 OBJECT ORIENTED PROGRAMMING
 
Ch06
Ch06Ch06
Ch06
 
Chap02
Chap02Chap02
Chap02
 
Course Breakup Plan- C
Course Breakup Plan- CCourse Breakup Plan- C
Course Breakup Plan- C
 
Csc153 chapter 03
Csc153 chapter 03Csc153 chapter 03
Csc153 chapter 03
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
 
FP 301 OOP FINAL PAPER
FP 301 OOP FINAL PAPER FP 301 OOP FINAL PAPER
FP 301 OOP FINAL PAPER
 
Database Management System-session 3-4-5
Database Management System-session 3-4-5Database Management System-session 3-4-5
Database Management System-session 3-4-5
 
BASIC CONCEPTS OF C++ CLASS 12
BASIC CONCEPTS OF C++ CLASS 12BASIC CONCEPTS OF C++ CLASS 12
BASIC CONCEPTS OF C++ CLASS 12
 
Csc253 chapter 09
Csc253 chapter 09Csc253 chapter 09
Csc253 chapter 09
 
Assignment5
Assignment5Assignment5
Assignment5
 
Chapter2
Chapter2Chapter2
Chapter2
 
Assignment2
Assignment2Assignment2
Assignment2
 
Oops Quiz
Oops QuizOops Quiz
Oops Quiz
 
Ch02
Ch02Ch02
Ch02
 
Ch13
Ch13Ch13
Ch13
 
Coursebreakup
CoursebreakupCoursebreakup
Coursebreakup
 
Ch04
Ch04Ch04
Ch04
 

Andere mochten auch

LinkedIn Infographic draft 11_1200
LinkedIn Infographic draft 11_1200LinkedIn Infographic draft 11_1200
LinkedIn Infographic draft 11_1200
AMComms
 
Konvergensi media satu_gadget_untuk_bany
Konvergensi media satu_gadget_untuk_banyKonvergensi media satu_gadget_untuk_bany
Konvergensi media satu_gadget_untuk_bany
Khaerudin Imawan
 

Andere mochten auch (20)

Ppt pik sistem peredaran
Ppt pik sistem peredaranPpt pik sistem peredaran
Ppt pik sistem peredaran
 
LinkedIn Infographic draft 11_1200
LinkedIn Infographic draft 11_1200LinkedIn Infographic draft 11_1200
LinkedIn Infographic draft 11_1200
 
Generator dc
Generator dcGenerator dc
Generator dc
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Gita Classi prime Scuola San Giovanni Bosco Imola
Gita Classi prime Scuola San Giovanni Bosco ImolaGita Classi prime Scuola San Giovanni Bosco Imola
Gita Classi prime Scuola San Giovanni Bosco Imola
 
ระบบ
ระบบระบบ
ระบบ
 
Who says 'everything's alright' (3)
Who says 'everything's alright'  (3)Who says 'everything's alright'  (3)
Who says 'everything's alright' (3)
 
Lemmy Koopa’s profile and biography information available at Super Luigi Bros...
Lemmy Koopa’s profile and biography information available at Super Luigi Bros...Lemmy Koopa’s profile and biography information available at Super Luigi Bros...
Lemmy Koopa’s profile and biography information available at Super Luigi Bros...
 
Diapositivas de Deportes
Diapositivas de Deportes Diapositivas de Deportes
Diapositivas de Deportes
 
ebay Today
ebay Todayebay Today
ebay Today
 
การใช้
การใช้การใช้
การใช้
 
Cyber Espionage and Insider Threat: House of Commons Panel Discussion
Cyber Espionage and Insider Threat: House of Commons Panel DiscussionCyber Espionage and Insider Threat: House of Commons Panel Discussion
Cyber Espionage and Insider Threat: House of Commons Panel Discussion
 
ความน่า
ความน่าความน่า
ความน่า
 
1. dasar pneumatik
1. dasar pneumatik1. dasar pneumatik
1. dasar pneumatik
 
الشروط والضوابط العامة للمشاركة في المؤتمر الطلابي السابع
الشروط والضوابط العامة للمشاركة في المؤتمر الطلابي السابعالشروط والضوابط العامة للمشاركة في المؤتمر الطلابي السابع
الشروط والضوابط العامة للمشاركة في المؤتمر الطلابي السابع
 
Carta de Atenas
Carta de AtenasCarta de Atenas
Carta de Atenas
 
Appilicious
AppiliciousAppilicious
Appilicious
 
ทั่วไป
ทั่วไปทั่วไป
ทั่วไป
 
Konvergensi media satu_gadget_untuk_bany
Konvergensi media satu_gadget_untuk_banyKonvergensi media satu_gadget_untuk_bany
Konvergensi media satu_gadget_untuk_bany
 
สารเคมีในเกษตรกรรมและอุตสาหกรรม
สารเคมีในเกษตรกรรมและอุตสาหกรรมสารเคมีในเกษตรกรรมและอุตสาหกรรม
สารเคมีในเกษตรกรรมและอุตสาหกรรม
 

Ähnlich wie Lecture 5

Ähnlich wie Lecture 5 (20)

Class 10
Class 10Class 10
Class 10
 
09. Methods
09. Methods09. Methods
09. Methods
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
static methods
static methodsstatic methods
static methods
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
 
CIS110 Computer Programming Design Chapter (9)
CIS110 Computer Programming Design Chapter  (9)CIS110 Computer Programming Design Chapter  (9)
CIS110 Computer Programming Design Chapter (9)
 
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: Modularity
 
C# p8
C# p8C# p8
C# p8
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
7494605
74946057494605
7494605
 
Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
Learn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsLearn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & Methods
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
Xamarin: C# Methods
Xamarin: C# MethodsXamarin: C# Methods
Xamarin: C# Methods
 

Mehr von Soran University (6)

Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Administrative
AdministrativeAdministrative
Administrative
 

Kürzlich hochgeladen

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 

Kürzlich hochgeladen (20)

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 

Lecture 5

  • 1. Methods(1) Lecture 5 Dr. Hakem Beitollahi Computer Engineering Department Soran University
  • 2.  Introduction  Math Class Methods  Methods  Method Definitions  Argument Promotion Methods(I)— 2
  • 3. Introdcution  Most computer programs that solve real-world problems are much larger than programs that you have written yet!  Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or modules.  Methods are the building blocks of C# and the place 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 by separating its tasks into self-contained units o Statements in method bodies are written only once  Reused from perhaps several locations in a program  Hidden from other methods  Avoid repeating code o Enable the divide-and-conquer approach o Reusable in other programs o User-defined or programmer-defined methods Methods(I)— 4
  • 5. Software engineering tip To promote software reusability, every method should be limited to performing a single, well-defined task, and the name of the method should express that task effectively. Such methods make programs easier to write, test, debug and maintain. A small method that performs one task is easier to test and debug than a larger method that performs many tasks. Methods(I)— 5
  • 6. Methods in C#  C# programs are written by combining new methods and classes  available in the .NET Framework Class Library (FCL)  The FCL provides:  mathematical calculations, string manipulations, 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 call o Called method either returns a result or simply returns to the caller o method calls form hierarchical relationships Methods(I)— 7
  • 8. Math Class Methods Methods(I)— 8
  • 9. Math Class Methods (I)  Math class methods allow the programmer to perform certain common mathematical calculations.  Methods are called by writing the name of the method, followed by a left parenthesis, the argument and a right parenthesis.  The parentheses may be empty, if we are calling a method that needs no information to perform its task. Return a double value  Example:  double x = Math.Sqrt( 900.0 ) Methods(I)— 9 Argument
  • 10. Software Engineering Observation 6.3  It is not necessary to add an assembly reference to use the Math class methods in a program. Class Math is located in namespace System, which is available to every program. Methods(I)— 10
  • 11. Math Class Methods (II) Methods(I)— 11
  • 13. Math Class Methods (III) Methods(I)— 13
  • 15. Method Definitions (I)  The general form of a function is ret-type method-name(parameter list) { body of the function }  The ret-type specifies the type of data that the method returns.  A method may return any type of data except an array.  The parameter list is a comma-separated list of variable names and their associated types that receive the values of the arguments when the function is called.  Methods must be declared within a class or a structure. 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 following syntax <<rreettuurrnn vvaalluuee>> <<nnaammee>> ((<<ppaarraammeetteerr lliisstt>>))  The method body is simply a C# code enclosed between { } Methods(I)— 17
  • 18. Method Example Methods(I)— 18 double computeTax(double income) { double taxes ; if (income < 5000.0) return 0.0; taxes = 0.07 * (income-5000.0); return taxes; } Function header Function body
  • 19. Method Definitions (IV)  Basic characteristics of methods are:  Return value type o output: data type or void  Method name o 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 parameters o inputs for the method o Empty parentheses indicate that the method requires no parameters.  Parentheses  Block of statements o The method block is surrounded with { } characters.  Access level o who can call the method Methods(I)— 19 Execute FindId SetName GetName CheckIfValid TestValidity
  • 20. Method Signature  The method signature is actually similar to the method header except in two aspects:  The parameters’ names may not be specified in the function signature  The method signature must be ended by a semicolon  Example Unnamed Parameter Semicolon ; double computeTaxes(double) ; double computeTaxes(double income) ; Methods(I)— 20
  • 21. Methods must be declared inside class Inside class every method should be public or private (later) This method return nothing (void) Define an object for calling the method Methods(I)— 21 Calling the method
  • 22. Method Definitions (V)  Each method must be defined inside a class or a struct.  It must have a name. In our case the name is ShowInfo.  The keywords that precede the name of the method are access specifier (public) and the return 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)— 23 static void Main() { ... } This is the Main() method. It is the entry point to each console or GUI application.  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 default one is used, which is private.
  • 24. Method Definitions (VII)  We create an instance of the Base class.  We call the ShowInfo() method upon the object.  The method is called by specifying the object instance, followed by the member access operator — the dot, followed by the method name. Methods(I)— 24 Base bs = new Base(); bs.ShowInfo();
  • 26. Example: Tax compute A method to compute tax Return type: double An input parameter (argument) : double Methods(I)— 26
  • 27. Example: Tax compute A method to get salary Return type: double An input parameter (argument) : string Methods(I)— 27
  • 28. Example: Tax compute A method to print tax Return type: void An input parameter (argument) : double Methods(I)— 28
  • 29. Example: Tax compute Define an object from class: ob ob.NameofMethod Calling the methods Methods(I)— 29
  • 30. More about Method parameters Methods(I)— 30
  • 31. Method Parameters  A parameter is a value passed to the method.  Methods can take one or more parameters.  If methods work with data, we must pass the data to the methods.  We do it by specifying them inside the parentheses.  In the method definition, we must provide a name and type for each parameter. Methods(I)— 31
  • 32. Example: Method parameters (I) Methods should be inside a class Methods(I)— 32
  • 33. Example: Method parameters (II) Method AddTwoValues Return type: int use the return keyword to return a value Input parameters: int a, int b Methods(I)— 33
  • 34. Example: Method parameters (III) Method AddThreeValues Return type: int use the return keyword to return a value Input parameters: int a, int b, int c Methods(I)— 34
  • 35. Example: Method parameters (IV) Define an object from class to call methods Calling methods Two methods return integer, so x and y should be integers Methods(I)— 35
  • 36. Methods inside the Main class (I)  Another Example: define methods inside the main class Methods(I)— 36 For methods inside the main class Access specifier: should be static
  • 37. Methods inside the Main class (II)  Another Example: define methods inside the main class No need to define an object. Directly use the name of method to call the method Methods(I)— 37
  • 38. Methods in Windows Application Forms Methods(I)— 38
  • 41. Common Programming Error 6.2  Defining a method outside the braces of a class definition is a syntax error. Methods(I)— 41
  • 42. Common Programming Error 6.3  Omitting the return-value-type in a method definition is a syntax error. If a method does not return a value, the method’s return-value-type must be void. Methods(I)— 42
  • 43. Common Programming Error 6.4  Forgetting to return a value from a method that is supposed to return a value is a syntax error. If a return-value-type other than void is specified, the method must contain a return statement that returns a value. Methods(I)— 43
  • 44. Common Programming Error 6.5  Returning a value from a method whose return type has been declared void is a syntax error Methods(I)— 44
  • 45. Common Programming Error 6.6  Placing a semicolon after the right parenthesis enclosing the parameter list of a method definition is a syntax error. Methods(I)— 45
  • 46. Common Programming Error 6.7  Redefining a method parameter in the method’s body is a syntax error. Methods(I)— 46
  • 47. Common Programming Error 6.9  Passing to a method an argument that is not compatible with the corresponding parameter’s type is a syntax error. Methods(I)— 47
  • 48. Common Programming Error 6.9  Defining a method inside another method is a syntax error (i.e., methods cannot be nested) Methods(I)— 48
  • 49.  Example: write a method to find maximum of three double values  Use windows application form Methods(I)— 49