CS6004NI Application Development: Samyush - Maharjan@islingtoncollege - Edu.np
CS6004NI Application Development: Samyush - Maharjan@islingtoncollege - Edu.np
Application Development
samyush
Samyush.maharjan@islingtoncollege.edu.np
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. }
| 3
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
4. {
name is a Parameter of SayHello method
5. Console.WriteLine($"Hello {name}!");
6. }
| 4
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. }
| 5
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:
1. class Program Optional Arguments
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. }
| 6
C# Method / Function
Controlling Parameters
| 7
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
| 8
C# Method / Function
Are the following statements True or False?
| 9
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
| 10
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;
| 11
C# Method / Function
Throwing 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);
| 12
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. }
| 13
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.
| 14
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.
| 15
C# Method / Function
Recursion
| 16
C# Method / Function
Recursion
RecursiveFactorial(4)
return 4 * RecursiveFactorial(4-1) 4 × 6 = 24
Using lambda expression with ternary operator:
int Factorial(int n) => n < 2 ? 1 : n * Factorial(n - 1); Main()
RecursiveFactorial(4) 24
| 17
C# Method / Function
Are the following statements True or False?
| 18
C# Method / Function
Are the following statements True or False?
| 19
Debugging during
Development
C# Debugging during Development
Using Visual Studio 2022
1. Click in the statement that declares the variable.
2. Navigate to Debug > Toggle Breakpoint or press F9.
| 21
C# Debugging during Development
Using Visual Studio 2022
3. Navigate to Debug > Start Debugging or press F5.
| 22
C# Debugging during Development
Using Visual Studio Code
For setting up Visual Studio Code for debugging follow the instructions from here.
1. Click in the statement that declares the variable.
2. Navigate to Run > Toggle Breakpoint or press F9.
| 23
C# Debugging during Development
Using Visual Studio Code
3. Navigate to View > Run.
4. At the top of the DEBUG window, click on the dropdown to the right of the Start Debugging button.
5. Select .NET Core Launch (console) (Debugging).
| 24
C# Debugging during Development
Using Visual Studio Code
6. Navigate navigate to Run > Start Debugging, or press F5.
| 25
C# Debugging during Development
Debugging Toolbar
• Continue/F5: continue running the program from the current position until it
ends or hits another breakpoint.
• Step Over/F10: the whole method is executed in one go and then suspends
execution at the first line of code after the called function returns.
• Step Into/F11: steps into the method and allows to step through every line in
that method.
• Step Out/Shift + F11: continues running code and suspends execution
when the current function returns.
• Restart/Ctrl or Cmd + Shift + F5: This button will stop and then immediately
restart the program with the debugger attached again.
• Stop/Shift + F5 (red square): This button will stop the debugging session.
| 26
C# Debugging during Development
Customizing Breakpoints
• Right-click the breakpoint and choose Edit Breakpoint / Conditions.
• Enter an expression which evaluate to a boolean value, such as the answer variable must be greater than 9.
• The break point is activated only when the expression which evaluate to true.
| 27
C# Debugging during Development
Customizing Breakpoints
• Edit the breakpoint or its conditions.
• Click Add condition in Visual Studio or select Hit Count in Visual Studio Code.
• Then enter a number such as 3, meaning that you would have to hit the breakpoint three times before it activates.
| 28
C# Debugging during Development
Customizing Breakpoints
• Hovering mouse over breakpoint (red circle) would show a summary of Expression and Hit Count.
| 29
C# Debugging during Development
Customizing Breakpoints
• Hovering mouse over breakpoint (red circle) would show a summary of Expression and Hit Count.
| 30
Questions?