Methods in C#
Methods are blocks of code that perform a specific task. They help in reusability, modularity, and readability of code.
1. Defining and Calling Methods
Defining a Method
Explanation:
static void GreetUser()→ Method with no return value and no parameters.GreetUser();→ Calling the method insideMain().
2. Method Parameters and Return Types
Methods can accept inputs (parameters) and return values.
Explanation:
int a, int b→ Parameters.return a + b;→ Returns the sum to the caller.- Method return type must match the
returnvalue type.
3. Method Overloading
Method overloading allows multiple methods with the same name but different parameters.
Explanation: Compiler decides which method to call based on parameter type or number.
4. Optional Parameters
Parameters can have default values, making them optional during method call.
5. ref, out, params Keywords
5.1 ref
Passes variable by reference, requires initialization before calling.
5.2 out
Passes variable by reference, does not require initialization before calling.
5.3 params
Allows variable number of arguments.
6. Recursion
A method can call itself; this is called recursion.
Explanation:
Factorial(5)→ 5 * 4 * 3 * 2 * 1 = 120- Recursion must have a base case to avoid infinite calls.
Summary of Chapter 4:
- Methods improve code modularity and reusability.
- Methods can have parameters and return values.
- Overloading allows multiple methods with the same name.
- Optional parameters simplify method calls.
- ref, out, params provide advanced parameter handling.
- Recursion allows a method to call itself, useful for mathematical and algorithmic problems.