A fundamental concept for structuring and reusing code.
📌 1. What is a Method?
A method is a block of code that performs a specific task.
-
Helps avoid repetition
-
Makes code modular and readable
-
Can accept parameters and return values
📌 2. Basic Syntax
[access_modifier] [return_type] MethodName([parameters])
{
// Method body
}-
access_modifier →
public,private,protected, etc. (who can access the method) -
return_type → data type the method returns (
voidif it returns nothing) -
MethodName → any valid identifier
-
parameters → input values (optional)
📌 3. Example: Void Method
// No return value
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
// Usage
Greet("Alice"); // Output: Hello, Alice!void→ method does not return anything
📌 4. Example: Method with Return Value
public int Add(int a, int b)
{
int sum = a + b;
return sum;
}
// Usage
int result = Add(5, 3);
Console.WriteLine(result); // 8-
int→ return type -
return→ sends the value back to the caller
📌 5. Method Overloading
You can define multiple methods with the same name but different parameters.
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b;
Console.WriteLine(Add(5, 3)); // 8 (int)
Console.WriteLine(Add(5.5, 3.2)); // 8.7 (double)- Compiler chooses the correct method based on parameter types
📌 6. Optional Parameters and Default Values
public void PrintMessage(string message = "Hello World")
{
Console.WriteLine(message);
}
PrintMessage(); // Hello World
PrintMessage("Hi there!"); // Hi there!📌 7. Expression-bodied Methods (C# 6+)
For short methods, you can use =>:
public int Square(int x) => x * x;
Console.WriteLine(Square(5)); // 25- Similar to lambda expressions but for named methods
📌 8. Pass by Reference vs Value
- By default, parameters are passed by value:
void Increment(int x)
{
x++;
}
int num = 5;
Increment(num);
Console.WriteLine(num); // 5 (unchanged)- To modify the original variable, use
reforout. See Difference Between Ref and Out:
void Increment(ref int x)
{
x++;
}
int num = 5;
Increment(ref num);
Console.WriteLine(num); // 6out→ similar torefbut must be initialized inside method. See Initialising Before Passing
📌 9. Summary Table
| Feature | Example / Notes |
|---|---|
No return (void) | void Greet() |
| Return value | int Add(int a, int b) |
| Parameters | (int a, int b) |
| Optional parameters | (string msg = "Hello") |
| Method overloading | Same name, different parameters |
| Expression-bodied method | int Square(int x) => x * x; |
| Pass by reference | ref or out |
✅ Tip:
-
Methods should do one thing and be reusable.
-
Keep parameter lists short and meaningful.