0% found this document useful (0 votes)
36 views19 pages

Lec 09 Methods 1

methods in c#

Uploaded by

omareldowiny17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views19 pages

Lec 09 Methods 1

methods in c#

Uploaded by

omareldowiny17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Mansoura University

Faculty of Computers and Information


Department of Computer Science
Fall 2024

[CS112] Structural Programming

Lecture 09: Methods – Part 1

1ST Year – General department

Muhammad Haggag Zayyan, Ph.D


Topics

 What is a Method?
 Basic Method Structure
 Components of a Method
 Method Return Types
 Method Overloading
 Call a Method
 Passing Arguments by value and by reference
 Optional Parameters
 Named Parameters
 Delegates
 Recursion

2
What is a Method?

 Definition: A method is a block of code that performs a specific task.


 Purpose: To organize code into reusable blocks.

 Basic Structure:
returnType MethodName(parameters)
{
// Method body
}

3
Motivation of Using Methods

Without Methods (Repetitive Code) With Methods (Using Methods to Avoid Repetition)

1. static void Main() {


1. // Method to calculate area of a rectangle
2. // Rectangle 1
2. static double CalculateArea(double length, double width) {
3. double length1 = 5;
3. return length * width;
4. double width1 = 10;
4. }
5. double area1 = length1 * width1;
5. static void Main() {
6. Console.WriteLine("Area of Rectangle 1: " + area1);
7. // Rectangle 2 6. // Using the method to calculate areas

8. double length2 = 7; 7. double area1 = CalculateArea(5, 10);

9. double width2 = 3; 8. Console.WriteLine("Area of Rectangle 1: " + area1);

10. double area2 = length2 * width2; 9. double area2 = CalculateArea(7, 3);


11. Console.WriteLine("Area of Rectangle 2: " + area2); 10. Console.WriteLine("Area of Rectangle 2: " + area2);
12. } 11. } 4
Benefits of Using Methods

 Reusability: The method CalculateArea can be reused for any rectangle without rewriting the same logic.
 Maintainability: If the formula for calculating the area changes, you only need to update the method, not every
occurrence in the code.
 Clarity: CalculateArea clearly tells you what the program is doing without needing to focus on the details of
how the calculation is performed. This is the power of abstraction in programming: it improves clarity by
separating the what from the how.
 Avoids Redundancy: No need to repeat the same code, making the program cleaner and easier to maintain.

5
Components of a Method

 Return Type: Type of data the method returns (e.g., void, int, string).
 Method Name: Unique identifier for the method.
 Parameters: Optional. Data passed into the method.
 Method Body: Contains the code executed when the method is called.

 Example:

1. int Add(int a, int b) // Add is the method name


2. {
3. return a + b; // Method body
4. }

6
Method Return Types

 void: Method does not return a value.


1. void DisplayMessage()
2. {
3. Console.WriteLine("Hello, World!");
4. }

 Non-void (e.g., int, string): Method returns a value of specified type.


1. int Multiply(int a, int b)
2. {
3. return a * b;
4. }

7
Method Overloading

 A method's signature consists of the method's name and the number and type of its parameters.
 Method Overloading is a concept where multiple methods have the same name but different parameters.
 The return type is not considered part of the method signature.

 Example of Overloading:
1. void PrintMessage(string message) {
2. Console.WriteLine(message);
3. }

1. void PrintMessage(int number) {


2. Console.WriteLine(number);
3. }
8
Method Overloading-2

 Overloaded methods are chosen at compile-time based on the number or types of arguments passed to them.

1. static void Main() {


2. Console.WriteLine(Add(3, 4)); // Calls the int version
3. Console.WriteLine(Add(3.5, 4.5)); // Calls the double version
4. }
5. static int Add(int a, int b) {
6. return a + b;
7. }
8. static double Add(double a, double b) {
9. return a + b;
10. }

9
Invalid Overloading based only on Return Type

 If you try to overload a method by only changing its return type, the C# compiler will throw an error because the
method signatures are not unique:
If overloading considered return
1. static int Calculate() type, the compiler couldn't decide
2. { which method to call, since the
return type alone doesn't clarify
3. return 42;
the intended action. Method
4. } overloading should be based on
5. // Invalid: Cannot overload based on return type alone parameters, which define the
6. static string Calculate() method's behavior.
7. {
8. return "Hello";
9. }

Compile-error: already defines a member called 'Calculate' with the same parameter types
10
Calling a Method

 Syntax to Call a Method:


MethodName(parameters);
 Example of Calling a Method:

int result = Add(5, 7); // Calling Add method and storing result

// If you don't need to store or use the return value, you can still call the method.
However, the result will be computed and then discarded after execution.
Add(5, 7);

11
Method Parameters

 Definition: Parameters are values passed to a method to use within its body.

 Types of Parameters:
o Value Parameters: Method parameters that get a copy of the argument value.
o Reference Parameters: Parameters passed by reference, using the ref or out keyword.
o Optional Parameters: Parameters with default values.
o Named Parameters: Passing arguments by explicitly specifying the parameter name, often in any order.

12
Passing Arguments By Value

 Value Parameters: A copy of the argument is passed, and changes inside the method do not affect the original value.

1. static void Main() {


2. int a = 15;
3. UpdateValue(a);
4. Console.WriteLine(a);
5. }
6. static void UpdateValue(int b) {
7. b = 30;
8. }

// Output: 15 (No change) 13


Passing Arguments By Reference - ref
 Using ref Keyword:
o Allows methods to modify the original value of the argument passed.
o Both method signature and method call must use ref.
o The argument must be initialized before it is passed to the method.
o The memory address of the original variable (not a copy) is passed to the method.

1. static void Main() {


2. int a = 15; // must initialize 'a'
3. UpdateValue(ref a);
4. Console.WriteLine(a);
5. }
6. static void UpdateValue(ref int b) {
7. b = 30; // variable 'b' can be assigned optionally
8. }
// Output: 30 14
Passing Arguments By Reference - out
 Using out Keyword:
o out allows a method to modify the argument passed.
o Both method signature and method call must use out.
o The argument does not need to be initialized before passing it.
o The method is required to assign a value to the argument.

1. static void Main() {


2. int a; // no need to initialize 'a' because we're using 'out'
3. UpdateValue(out a);
4. Console.WriteLine(a);
// Output: 30
5. }
6. static void UpdateValue(out int b) {
7. b = 30; // 'b' must be assigned inside the method
8. } 15
ref vs out

 Initialization:
o ref: The variable passed to the method must be initialized before the method is called.
o out: The variable passed to the method does not need to be initialized before the method is called.

 Method Behavior:
o ref: The method can modify the passed argument, but the argument must already have a value when passed.
o out: The method must assign a value to the argument before the method completes, and the argument can be treated as
uninitialized before the call.

16
Passing an Array by Value (Default)
 When array is passed by value to a method, the method receives a reference to the original array. However, this does not mean that the
array itself is passed by reference. Any changes made to the elements of the array will affect the original array, but reassigning the array
itself (i.e., pointing it to a new array) will not affect the original array.

1. static void Main() {


2. int[] arr = { 1, 2, 3 };
3. // Pass by value (array reference is copied)
4. ModifyArray(arr);
5. // Changes to array elements affect the original array
6. Console.WriteLine(string.Join(", ", arr));
7. }
8. static void ModifyArray(int[] arrByVal) {
9. arrByVal[0] = 10; // Modify element, changes the original array
10. arrByVal = new int[] { 4, 5, 6 }; // Reassigning array doesn't affect the original array
11. }
string.Join: A static method of the string class in C# that joins the
// Output: 10, 2, 3 elements of a collection (such as an array or list) into a single string, with a
17
separator between the elements.
Passing an Array by Reference (ref)
 To explicitly pass the reference to the array and allow the method to modify the array reference itself (e.g., changing it to a new
array), you can use the ref keyword. This way, any reassignment of the array inside the method will affect the original array
outside the method.

1. static void Main() {


2. int[] arr = { 1, 2, 3 };
3. // Pass array by reference (allows modifying the array reference)
4. ModifyArray(ref arr);
5. // The original array reference is changed
6. Console.WriteLine(string.Join(", ", arr));
7. }
8. static void ModifyArray(ref int[] arrByRef) {
9. arrByRef = new int[] { 4, 5, 6 }; // Reassign the reference to a new array
10. }

// Output: 4, 5, 6 18
Thank you

You might also like