0% found this document useful (0 votes)
3 views

03 MethodFunction

Uploaded by

Prashant Gc
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

03 MethodFunction

Uploaded by

Prashant Gc
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

CS6004NI

Application Development
Samyush
samyush.com.np
[email protected]
https://github.com/Samyush
C# Method / Function
C# Method / Function
Introduction
A function is called method when it is a part of a object/class. A method/function let us
use name and reuse a chunk of code.
returnType MethodName() {
// method body
}

Example:
1. class Hello
2. {
3. void PrintHelloWorld()
4. {
5. Console.WriteLine("Hello World!");
6. }
7. }

| 4
C# Method / Function
Parameters and Arguments
Parameters are the variable names listed in the function’s definition and Arguments are the values
passed to the function.

Example:
1. class Program
2. {
3. void SayHello(string name) // Method definition name is a Parameter of SayHello
4. { method
5. Console.WriteLine($"Hello {name}!");
6. }

7. static void Main(string[] args)


8. {
9. var p = new Program(); "John" is an Argument to a SayHello method call
10. p.SayHello("John"); // Method call
11. }
12. }

| 5
C# Method / Function
Named Arguments
Named arguments allow us to specify an argument for a parameter by matching the argument with its name
rather than with its position in the parameter list.

Example:
1. class Program
2. {
3. void PrintIntro(string name, string companyName, string jobTitle)
4. {
5. Console.WriteLine($"Hi! I'm {name}. I work at {companyName} as a {jobTitle}.");
6. }

7. static void Main(string[] args)


8. {
9. var p = new Program();
10. p.PrintIntro("John", "Google", "QA Engineer");
11. p.PrintIntro("John", jobTitle:"QA Engineer", companyName:"Google"); // Same as above
12. }
Named Arguments
13. }

| 6
C# Method / Function
Optional Arguments
Optional arguments allow us to omit arguments for some parameters. Both techniques can be used with
methods, indexers, constructors, and delegates.

Example: Optional Arguments


1. class Program
2. {
3. void PrintIntro(string name, string companyName="Google", string jobTitle="QA Engineer")
4. {
5. Console.WriteLine($"Hi! I'm {name}. I work at {companyName} as a {jobTitle}.");
6. }

7. static void Main(string[] args)


8. {
9. var p = new Program();
10. p.PrintIntro("John", "Google", "Software Engineer");
11. p.PrintIntro("John", jobTitle:"Software Engineer"); // Same as above
12. }
13. }

| 7
C# Method / Function
Controlling Parameters

A parameter can be passed in a method one of three ways:


1. By value (default): When passing a variable as a parameter by default, its current value gets passed, not the variable
itself.

returnType MethodName(type parameterName)


2. By reference as a ref parameter: When passing a variable as a ref parameter, a reference to the variable gets passed
into the method. It requires that the variable be initialized before it is passed.

returnType MethodName(ref type refParameterName)


3. As an out parameter: When passing a variable as an out parameter, a reference to the variable gets passed into the
method. It requires that the a value is assigned before the method returns.

returnType MethodName(out type outParameterName)

| 8
C# Method / Function
Controlling Parameters
Example:
1. void PassingParameters(int x, ref int y, out int z)
2. {
3. x++;
4. y++;
5. z = 30; // must be initialized inside the method
6. z++;
7. }
8. ...
9. var p = new Program();
10. int a = 10;
11. int b = 20;
12. Console.WriteLine($"Before: a = {a}, b = {b}"); // Before: a = 10, b = 20
13. p.PassingParameters(a, ref b, out int c);
14. Console.WriteLine($"After: a = {a}, b = {b}, c = {c}"); // After: a = 10, b = 21, c = 31

| 9
C# Method / Function
Are the following statements True or False?

1. “Optional parameters must appear after all required parameters.”

2. “Named arguments must be passed in the correct positional order.”

3. “Named arguments can be used after positional arguments.”

4. “A ref or out parameter cannot have a default value.”

| 10
C# Method / Function
Are the following statements True or False?

1. “Optional parameters must appear after all required parameters.” => True

2. “Named arguments must be passed in the correct positional order.” => False

3. “Named arguments can be used after positional arguments.” => True

4. “A ref or out parameter cannot have a default value.” => True

| 11
C# Method / Function
Returning Value
A return value allows a method to produce a result when it completes.
Example:
1. string GetFullName(string firstName, string lastName)
2. {
3. if (lastName == "")
4. return firstName;
5. if (firstName == "")
6. return lastName;

7. var fullName = $"{firstName} {lastName}";


8. return fullName;
9. }
10. ...
11. var p = new Program();
12. string fullName = p.GetFullName("John", "Doe");
13. Console.WriteLine(fullName); // John Doe

| 12
C# Method / Function
Throwing Exceptions
The other side of Try-catch, creating and throwing new exceptions.

Example:
1. string GetFullName(string firstName, string lastName)
2. {
3. if (firstName == null || lastName == null)
4. throw new Exception("I can't deal with null!");
5. if (lastName == "")
Unhandled exception. System.Exception: I can't deal with null!
6. ... at Program.GetFullName(String firstName, String lastName)
at Program.Main(String[] args)
7. } Command terminated by signal 6
8. ...
9. var p = new Program();
10. string fullName = p.GetFullName("John", null);

| 13
C# Method / Function
Throwing Exceptions
Re-throwing an Exceptions Example:
1. string GetFullName(string firstName, string lastName)
2. {
3. if (firstName == null || lastName == null)
4. throw new Exception("I can't deal with null!");
5. if (lastName == "")
6. ...
7. try
8. {
9. var p = new Program();
10. string fullName = p.GetFullName("John", null);
11. Console.WriteLine(fullName);
12. }
13. catch (Exception ex)
14. {
15. Console.WriteLine($"Error Message = {ex.Message}"); // Error Message = I can't deal with null!
16. throw; // Re-throws the Exception
17. }

| 14
C# Method / Function
Common Exception Types

Exception Name Meaning

NotImplementedException The programmer hasn’t written this code yet.

NotSupportedException I will never be able to do this.

InvalidOperationException I can’t do this in my current state, but I might be able to in another state.

ArgumentOutOfRangeException This argument was too big (too small, etc.) for me to use.

ArgumentNullException This argument was null, and I can’t work with a null value.

ArgumentException Something is wrong with one of your arguments.

Exception Something went wrong, but I don’t have any real info about it.

| 15
C# Method / Function
Local Function
Local functions are nested in another method or function. They can only be called from their containing method/function.
Example:
1. class Program
2. {
3. static void Main(string[] args)
4. {
5. int sum = Add(5, 10); // Local function call
6. int product = Multiply(5, 10); // Local lambda function call
7. Console.WriteLine($"The sum is {sum} and the product is {product}."); // The sum is 15 and the product is 50.

8. int Add(int x, int y) // Local function


9. {
10. return x + y;
11. }

12. int Multiply(int x, int y) => x * y; // Local lambda function


13. }
14. }

| 16
C# Method / Function
Recursion
Recursion is when a method calls itself.

Factorial Iterative Example:


1. int IterativeFactorial(int n)
2. {
3. var result = 1;
Call Stack
4. while (n > 0)
5. {
6. result *= n;
IterativeFactorial(4)
result = 1
7. n--; while-loop
8. } calculate result
9. return result; return result 24
10. }
Main()
11. ...
IterativeFactorial(4) 24
12. var p = new Program();
13. p.IterativeFactorial(4); // 4! = 4 × 3 × 2 × 1 = 24

| 17
C# Method / Function
Recursion
Factorial Recursive Example:
1. int RecursiveFactorial(int n) Call Stack

2. {
3. if (n < 2)
RecursiveFactorial(1)
4. return 1; return 1 1
5. return n * RecursiveFactorial(n - 1);
RecursiveFactorial(2)
6. } return 2 * RecursiveFactorial(2-1) 2×1=2
7. ... RecursiveFactorial(3)
8. var p = new Program(); return 3 * RecursiveFactorial(3-1) 3×2=6
9. p.RecursiveFactorial(4); // 4! = 4 × 3 × 2 × 1 = 24 RecursiveFactorial(4)
return 4 * RecursiveFactorial(4-1) 4 × 6 = 24

Main()
Using lambda expression with ternary operator: RecursiveFactorial(4) 24
int Factorial(int n) => n < 2 ? 1 : n * Factorial(n - 1);

| 18
C# Method / Function
Are the following statements True or False?

1. “A function can have only one return statement.”

2. “A function must return a value.”

3. “Unhandled exception terminates the program.”

4. “ The base case condition is optional in a recursive function.”

| 19
C# Method / Function
Are the following statements True or False?

1. “A function can have only one return statement.” => False

2. “A function must return a value.” => False

3. “Unhandled exception terminates the program.” => True

4. “ The base case condition is optional in a recursive function.” => False

| 20

You might also like