5. Function
5. Function
1
Objectives
2
Introduction
What Is a Function?
▸Functions are virtually identical to methods, used for grouping together a
sequence of statements to perform a particular action or compute a
particular result. In fact, frequently, method and function are used
interchangeably.
▸Guidelines:
- DO give methods names that are verbs or verb phrases.
3
Functions/Methods
Types of function
▸Types:
- Built-in Functions
- User-Defined Functions
▸The function which is already defined in the framework and available to
be used by the developer or programmer is called a built-in function,
whereas if the function is defined by the developer or programmer
explicitly, then it is called a user-defined function.
Built-in Functions
User-Defined Functions
4
Functions/Methods
Declaration
▸Syntax
<Access_Modifier> <return_type> <method_name>([<param_list>])
▸Example
6
Functions/Methods
Different Parts of a Function
7
Functions/Methods
Function Signature
▸In C#, a Function/Method Signature is consisting of two things:
- the Method Name and
- the Parameter List.
▸The return type is not considered to be a part of the method signature.
▸ Example
8
Functions/Methods
Invocation
▸When we invoke a method, the control gets transferred to the called
method. Then the called method returns the control to the caller method
(from where we call the method) in the following three conditions.
- When the return statement is executed.
- When it reaches the method ending closing curly brace.
- When it throws an exception that is not handled in the called method.
9
Functions/Methods
Parameters and Arguments
▸A method can take any
number of parameters, and
each parameter is of a
specific data type.
▸The values that the caller
supplies for parameters are
called the arguments; every
argument must correspond
to a particular parameter.
10
Functions/Methods
Named parameters
▸Named parameters allow programmers to pass values to the parameters
of a method by referring to the names of the parameters.
▸You may or may not pass the parameters in the order in which they are
defined in the method signature. Here is an example of how to use named
parameters in C#:
11
Functions/Methods
Parameter Types
▸Value Parameters
▸Reference parameters
- Reference Parameters (ref)
- Output Parameters (out)
- Read-Only Pass by Reference (in)
- Return by Reference
▸You apply one of the following modifiers to a parameter declaration to
pass arguments by reference instead of by value:
- ref: The argument must be initialized before calling the method. The method can
assign a new value to the parameter but isn't required to do so.
- out: The calling method isn't required to initialize the argument before calling the
method. The method must assign a value to the parameter.
- readonly ref: The argument must be initialized before calling the method. The
method can't assign a new value to the parameter.
- in: The argument must be initialized before calling the method. The method can't
assign a new value to the parameter. The compiler might create a temporary variable
to hold a copy of the argument to in parameters.
12
Functions/Methods
Parameter Types - Value Parameters
▸Arguments to method calls are usually passed by value, which means the
value of the argument expression is copied into the target parameter.
13
Functions/Methods
Parameter Types - Reference Parameters (ref)
▸The ref modifier assigns a parameter to refer to an existing variable on the
stack rather than creating a new variable and copying the argument value
into the parameters.
14
Functions/Methods
Parameter Types - Output Parameters (out)
15
Functions/Methods
Parameter Types - Read-Only Pass by Reference (in)
▸In C# 7.2, support was added for passing a value type by reference that
was read only.
▸Rather than passing the value type to a function so that it could be
changed, read-only pass by reference was added: It allows the value type
to be passed by reference so that not only copy of the value type occurs
but, in addition, the invoked method cannot change the value.
▸In other words, the purpose of the feature is to reduce the memory
copied when passing a value while still identifying it as read only, thus
improving the performance.
▸This syntax is to add an in modifier to the parameter.
16
Functions/Methods
Parameter Types - Return by Reference
17
Functions/Methods
Method Overloading
▸A class can comprise many methods with the same name with a unique
signature→ Method overloading.
- Method signature includes:
• parameter data types,
• number of parameters,
• order of parameters
▸Method overloading is a type of operational polymorphism.
18
Functions/Methods
Optional parameters
▸Optional parameters allow the association of a parameter with a constant
value as part of the function/method declaration; it is possible to call a
function/method without passing an argument for every parameter.
19
Functions/Methods
Variable arguments (VarArgs)
▸VarArgs is a technique that allows you to pass varying numbers of
arguments to a function/method.
- Using params keyword while declare the parameter.
▸NOTE: No other parameters are permitted after the params keyword in a
method declaration, and only one params keyword is permitted in a
method declaration.
20
Functions/Methods
Exercises
1. Write a Python function to find the maximum of three numbers.
2. Write a Python function to sum all the numbers in a list.
3. Write a Python program to reverse a string.
4. Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument.
5.Write a Python function that takes a number as a parameter and checks
whether the number is prime or not.
6.Write a Python function to print
1. all prime numbers that less than a number (enter prompt keyboard).
2. the first N prime numbers
7.Write a Python function to check whether a number is "Perfect" or not.
Then print all perfect number that less than 1000.
8. Write a Python function to check whether a string is a pangram or not.
▸ (Note : Pangrams are words or sentences containing every letter of the alphabet at
least once. For example : "The quick brown fox jumps over the lazy dog"
21
Basic Error Handling with Exceptions
22
Exception Handling
Introduction
▸An exception is a problem that arises during the execution of a program. A
C# exception is a response to an exceptional circumstance that arises
while a program is running, such as an attempt to divide by zero.
▸Exceptions provide a way to transfer control from one part of a program
to another. C# exception handling is built upon four keywords: try, catch,
finally, and throw.
- try − A try block identifies a block of code for which particular exceptions is activated.
It is followed by one or more catch blocks.
- catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
- finally − The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
- throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
23
Exception Handling
Syntax and Exception classes
No. Exception Class & Description
▸Syntax System.IO.IOException
1
Handles I/O errors.
System.IndexOutOfRangeException
2 Handles errors generated when a method refers to an array
index out of range.
System.ArrayTypeMismatchException
3 Handles errors generated when type is mismatched with
the array type.
System.NullReferenceException
4
Handles errors generated from referencing a null object.
System.DivideByZeroException
5 Handles errors generated from dividing a dividend with
zero.
System.InvalidCastException
6
Handles errors generated during typecasting.
System.OutOfMemoryException
7
Handles errors generated from insufficient free memory.
System.StackOverflowException
8
Handles errors generated from stack overflow.
24
Exception Handling
Handling Exceptions
25