Chapter 10: Methods
1. What is a Method? (Super Simple Explanation)
A method is a named block of code that:
- Does a specific job
- Can take input (parameters)
- Can give back output (return value)
- Can be called (invoked) many times from different places
Syntax (basic):
|
0 1 2 3 4 5 6 7 8 9 10 |
returnType MethodName(parameters) { // code here return someValue; // if not void } |
2. Basic Method – No Parameters, No Return
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Person { public void Greet() { Console.WriteLine("Hello! Nice to meet you! 😊"); } } // Usage Person p = new Person(); p.Greet(); // Prints: Hello! Nice to meet you! 😊 |
3. Parameters – Sending Data Into Methods
Parameters are inputs the method needs to do its job.
A. Value Parameters (Most Common – Default)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
public void SayHello(string name) { Console.WriteLine($"Hello, {name}! Welcome to Hyderabad! 🌆"); } // Call it SayHello("Webliance"); // Hello, Webliance! Welcome... SayHello("Rahul"); // Hello, Rahul! Welcome... |
Important: When you pass a value type (int, double, bool, struct), it’s passed by value → a copy is made → changing it inside method doesn’t affect original.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
void IncreaseAge(int age) { age = age + 5; // Only changes the copy! Console.WriteLine($"Inside method: {age}"); } int myAge = 25; IncreaseAge(myAge); Console.WriteLine($"Original age: {myAge}"); // Still 25! |
B. ref Parameter – Pass by Reference (Change Original Value)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
void IncreaseAge(ref int age) { age = age + 5; // Changes the original! } int myAge = 25; IncreaseAge(ref myAge); Console.WriteLine(myAge); // Now 30! |
C. out Parameter – Method Must Assign a Value
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
void GetBirthYear(out int birthYear) { birthYear = DateTime.Now.Year - 25; // Must assign! } int year; GetBirthYear(out year); Console.WriteLine($"Born in {year}"); |
Common pattern: TryParse uses out
|
0 1 2 3 4 5 6 7 8 9 |
if (int.TryParse("123", out int number)) { Console.WriteLine(number); // 123 } |
D. params Parameter – Variable Number of Arguments
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
void PrintFriends(params string[] friends) { Console.WriteLine("My friends are:"); foreach (string friend in friends) { Console.WriteLine($"- {friend}"); } } PrintFriends("Rahul", "Priya", "Amit"); PrintFriends("Sneha"); // Works with one PrintFriends(); // Works with zero! |
4. Return Types – Getting Data Back from Methods
Methods can return any type (or nothing → void)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public int Add(int a, int b) { return a + b; } int result = Add(10, 20); // 30 public string GetGreeting(string name) { return $"Hello, {name}! How are you today? 😊"; } |
Multiple returns? → Use out or return a class/tuple
5. Method Overloading – Same Name, Different Parameters
Same method name, different parameter list (number, type, or order)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } public string Add(string a, string b) { return a + b; // Concatenation } } // All valid calls var calc = new Calculator(); calc.Add(5, 3); // int version calc.Add(5.5, 3.2); // double version calc.Add(1, 2, 3); // three ints calc.Add("Hello", "World"); // string version |
6. Optional / Default Parameters (Very Useful!)
You can give default values – caller can skip them
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
void OrderFood(string dish, int quantity = 1, string spiceLevel = "Medium") { Console.WriteLine($"Ordering {quantity} {dish}(s) with {spiceLevel} spice."); } OrderFood("Biryani"); // 1 Biryani, Medium OrderFood("Pizza", 2); // 2 Pizzas, Medium OrderFood("Pasta", spiceLevel: "Spicy"); // 1 Pasta, Spicy OrderFood("Dosa", 3, "No Spice"); // All specified |
Rule: Optional parameters must come after required ones.
7. Mini-Project: Smart Bank Account with Methods
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
class BankAccount { public string Holder { get; } public decimal Balance { get; private set; } public BankAccount(string holder, decimal initial = 0) { Holder = holder; Balance = initial >= 0 ? initial : 0; } public void Deposit(decimal amount) { if (amount <= 0) throw new ArgumentException("Amount must be positive!"); Balance += amount; Console.WriteLine($"Deposited ₹{amount:N2}. New balance: ₹{Balance:N2}"); } public bool Withdraw(decimal amount, out decimal remaining) { remaining = Balance; if (amount <= 0) { Console.WriteLine("Amount must be positive!"); return false; } if (amount > Balance) { Console.WriteLine("Insufficient funds!"); return false; } Balance -= amount; remaining = Balance; Console.WriteLine($"Withdrew ₹{amount:N2}. Remaining: ₹{Balance:N2}"); return true; } public decimal CalculateInterest(decimal ratePercent = 4.5m) { return Balance * (ratePercent / 100m); } public void ShowBalance() => Console.WriteLine($"Current balance: ₹{Balance:N2}"); } // Usage var account = new BankAccount("Webliance", 10000); account.Deposit(5000); account.Withdraw(3000, out decimal left); account.ShowBalance(); // ₹12,000.00 decimal interest = account.CalculateInterest(); // 4.5% default Console.WriteLine($"Yearly interest (4.5%): ₹{interest:N2}"); |
Quick Cheat Sheet – Methods
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Value param void Print(string text) { ... } // ref / out void Swap(ref int a, ref int b) { ... } bool TryGet(out int value) { ... } // params void Sum(params int[] numbers) { ... } // Optional void Greet(string name, string city = "Hyderabad") { ... } // Overload int Add(int a, int b) { ... } double Add(double a, double b) { ... } |
Your Homework (Super Practical!)
- Create a new console project called MethodMaster
- Create a class Student with:
- Properties: Name, RollNumber, Marks (array or List<double>)
- Method: AddMark(double mark) – add a mark
- Method: GetAverage() – return average (use params or List)
- Method: PrintReport(string title = “Student Report”) – optional title
- Overloaded AddMark for single mark or multiple (params)
- In Program.cs: Create a student, add 5 marks, print average and report
Next lesson: Access Modifiers & Encapsulation – we’re going to learn how to protect our data and make classes professional!
You’re doing absolutely fantastic! 🎉 Any part of methods confusing? Want more examples with ref, out, or overloading? Just tell me — I’m right here for you! 💙
