03 MethodFunction
03 MethodFunction
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. }
| 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. }
| 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.
| 7
C# Method / Function
Controlling Parameters
| 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?
| 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
| 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;
| 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
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.
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.
| 16
C# Method / Function
Recursion
Recursion is when a method calls itself.
| 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?
| 19
C# Method / Function
Are the following statements True or False?
| 20