Methods Deep Dive
How to Make Your Classes Do Things
Making Your Classes Do Things
In Lesson 1, we learned about classes. In Lesson 2, we learned about storing data. Now let's learn how to make our classes do things using Methods!
- Fields/Properties = What a class has (data)
- Methods = What a class does (actions)
Why are methods useful? They help you organize your code, reuse logic, and make your programs easier to understand and maintain.
Step 1: What is a Method?
A method is a block of code that performs a specific task.
Method Parts
A method has several parts:
// [1] [2] [3] [4] [5]
public int Add(int a, int b)
{
return a + b; // [6]
}
- [1] public - Who can use it
- [2] int - What it returns (or
voidif nothing) - [3] Add - Name of the method
- [4] (int a, int b) - Parameters (inputs)
- [5] { } - Code block (the action)
- [6] return - Gives back a result
Using a Method
You call a method by using its name and giving it inputs:
Calculator calc = new Calculator();
int result = calc.Add(5, 3); // result = 8
Console.WriteLine(result); // Output: 8
Step 2: Types of Methods
Methods with Return Values
These methods give back a result:
public int Add(int a, int b)
{
return a + b; // Returns a number
}
public string GetName()
{
return "John"; // Returns text
}
public bool IsValid(int age)
{
return age > 0; // Returns true/false
}
calculator.Add(5, 3) gives you 8
Void Methods (No Return)
These methods do something but don't give back a result:
public void SayHello()
{
Console.WriteLine("Hello!");
}
public void SaveToFile(string data)
{
// Code to save data
}
printer.Print("Hello") - it prints, but gives nothing back
return needed
Step 3: Method Parameters (Inputs)
Parameters are the inputs you give to a method.
Value Parameters
What: Passes a copy of the data
public void ChangeValue(int number)
{
number = 100; // Only changes the copy
}
// Usage:
int x = 5;
ChangeValue(x);
Console.WriteLine(x); // Still 5! (not changed)
Reference Parameters (ref)
What: Passes a reference to the data
public void ChangeValue(ref int number)
{
number = 100; // Changes the original
}
// Usage:
int x = 5;
ChangeValue(ref x);
Console.WriteLine(x); // Now 100! (changed)
Output Parameters (out)
What: Returns multiple values from a method
public bool TryDivide(int a, int b, out int result)
{
if (b == 0)
{
result = 0;
return false; // Failed
}
result = a / b;
return true; // Success
}
// Usage:
if (TryDivide(10, 2, out int quotient))
{
Console.WriteLine($"Result: {quotient}"); // Result: 5
}
Optional Parameters
What: Parameters with default values
public void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
// Usage:
Greet("John"); // Hello, John!
Greet("Jane", "Hi"); // Hi, Jane!
Step 4: The Params Keyword
The params keyword lets you pass any number of parameters.
What is Params?
It allows a method to accept any number of arguments:
public int Sum(params int[] numbers)
{
int total = 0;
foreach (int num in numbers)
total += num;
return total;
}
// Usage - pass ANY number!
int result1 = Sum(1, 2, 3); // 6
int result2 = Sum(1, 2, 3, 4, 5); // 15
int result3 = Sum(); // 0 (empty)
When to Use Params
- ✅ When you don't know how many items you'll get
- ✅ For utility methods like
Sum,Average,Max - ✅ When the input is optional
params parameter, and it must be the last parameter.
Step 5: Method Overloading
Overloading means having multiple methods with the same name but different parameters.
Overloaded Methods
public class MathOperations
{
// Version 1: Two integers
public int Add(int a, int b)
{
return a + b;
}
// Version 2: Two doubles
public double Add(double a, double b)
{
return a + b;
}
// Version 3: Three integers
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
Using Overloaded Methods
MathOperations math = new MathOperations();
// C# automatically picks the right one!
int result1 = math.Add(5, 3); // Uses int version
double result2 = math.Add(5.5, 3.2); // Uses double version
int result3 = math.Add(5, 3, 2); // Uses three-parameter version
Step 6: Static vs Instance Methods
Instance Methods
What: Belong to an object (need an instance)
public class Person
{
public string Name { get; set; }
// Instance method
public void SayHello()
{
Console.WriteLine($"Hello, I'm {Name}");
}
}
// Usage - need an object!
Person p = new Person { Name = "John" };
p.SayHello(); // ✅ Works
Each object has its own copy
Static Methods
What: Belong to the class itself (no object needed)
public class MathHelper
{
// Static method
public static int Add(int a, int b)
{
return a + b;
}
}
// Usage - no object needed!
int result = MathHelper.Add(5, 3); // ✅ Works without creating an object
Shared by all objects
Math.Sqrt(), Convert.ToInt32(),
or methods that don't need object data.
Step 7: Expression-Bodied Methods (Shortcut)
For simple methods that only have one line, you can use a shortcut.
Regular Method (Long Way)
public int Add(int a, int b)
{
return a + b;
}
public bool IsEven(int number)
{
return number % 2 == 0;
}
⚠️ Lot of code for simple logic!
Expression-Bodied (Short Way)
// Use => (arrow) for single line methods
public int Add(int a, int b) => a + b;
public bool IsEven(int number) => number % 2 == 0;
public void Print(string msg) => Console.WriteLine(msg);
Real-World Example: Student Manager
Let's build a complete StudentManager class with all types of methods:
StudentManager.cs
using System;
using System.Collections.Generic;
public class StudentManager
{
// Private field to store students
private List<string> students = new List<string>();
// 1. Add a student (void method)
public void AddStudent(string name)
{
// Validate input
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name cannot be empty!");
students.Add(name);
Console.WriteLine($"✅ Student '{name}' added successfully.");
}
// 2. Remove a student (returns bool)
public bool RemoveStudent(string name)
{
if (students.Remove(name))
{
Console.WriteLine($"❌ Student '{name}' removed.");
return true;
}
Console.WriteLine($"⚠️ Student '{name}' not found.");
return false;
}
// 3. Find a student (using out parameter)
public bool FindStudent(string name, out int index)
{
index = students.IndexOf(name);
return index >= 0;
}
// 4. Get student at index (with validation)
public string GetStudent(int index)
{
if (index < 0 || index >= students.Count)
throw new ArgumentOutOfRangeException("Invalid index!");
return students[index];
}
// 5. Get all students (returns array)
public string[] GetAllStudents() => students.ToArray();
// 6. Get count (read-only property)
public int Count => students.Count;
// 7. Clear all (void method)
public void Clear() => students.Clear();
// 8. Display all students
public void DisplayAll()
{
if (students.Count == 0)
{
Console.WriteLine("📭 No students in the list.");
return;
}
Console.WriteLine($"\n📚 Students ({Count} total):");
for (int i = 0; i < students.Count; i++)
{
Console.WriteLine($" {i + 1}. {students[i]}");
}
Console.WriteLine();
}
}
Program.cs (Using the Manager)
using System;
class Program
{
static void Main()
{
Console.WriteLine("🎓 STUDENT MANAGEMENT SYSTEM");
Console.WriteLine("═══════════════════════════════════\n");
// Create manager
StudentManager manager = new StudentManager();
// Add students
manager.AddStudent("Alice");
manager.AddStudent("Bob");
manager.AddStudent("Charlie");
manager.AddStudent("Diana");
// Display all
manager.DisplayAll();
// Find a student using out parameter
if (manager.FindStudent("Bob", out int index))
{
Console.WriteLine($"✅ Bob found at position {index + 1}");
}
// Remove a student
manager.RemoveStudent("Charlie");
manager.RemoveStudent("Unknown"); // This will show "not found"
Console.WriteLine();
manager.DisplayAll();
// Get a specific student
try
{
string student = manager.GetStudent(0);
Console.WriteLine($"👤 First student: {student}");
// This will throw an error
string invalid = manager.GetStudent(99);
}
catch (Exception ex)
{
Console.WriteLine($"❌ Error: {ex.Message}");
}
Console.WriteLine($"\n📊 Total students: {manager.Count}");
}
}
- ✅ Void methods (AddStudent, DisplayAll)
- ✅ Return methods (GetStudent, GetAllStudents)
- ✅ out parameter (FindStudent)
- ✅ Validation (checking invalid inputs)
- ✅ Expression-bodied method (GetAllStudents)
- ✅ Read-only property (Count)
What You Learned Today
Methods
Actions your class can do
Parameters
Inputs for methods
Overloading
Same name, different inputs
Static
Methods without objects
Exercise: Create an Inventory Manager
Your Task:
Create an InventoryManager class with the following:
Requirements:
-
AddItem - Add an item with name and quantity
- Optional price parameter (default 0)
- Validate that name is not empty
- Validate quantity is positive
-
RemoveItem - Remove item by name
- Returns true if removed
- Returns false if not found
-
FindItem - Find item by name
- Uses
outparameter to return quantity - Returns true if found
- Uses
More Requirements:
-
UpdateQuantity - Update quantity by name
- New quantity must be positive
- Returns true if updated
-
GetTotalValue - Calculate total value of all items
- Uses price * quantity for each item
- DisplayInventory - Show all items with formatting
- Count - Read-only property for item count
// InventoryManager.cs
using System;
using System.Collections.Generic;
public class InventoryManager
{
// Store items with their data
private Dictionary<string, (int quantity, decimal price)> items =
new Dictionary<string, (int, decimal)>();
// 1. Add item
public void AddItem(string name, int quantity, decimal price = 0)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name cannot be empty!");
if (quantity <= 0)
throw new ArgumentException("Quantity must be positive!");
if (price < 0)
throw new ArgumentException("Price cannot be negative!");
items[name] = (quantity, price);
Console.WriteLine($"✅ Added: {name} (Qty: {quantity}, Price: ${price:F2})");
}
// 2. Remove item
public bool RemoveItem(string name)
{
if (items.Remove(name))
{
Console.WriteLine($"❌ Removed: {name}");
return true;
}
Console.WriteLine($"⚠️ Item '{name}' not found.");
return false;
}
// 3. Find item
public bool FindItem(string name, out int quantity, out decimal price)
{
if (items.TryGetValue(name, out var item))
{
quantity = item.quantity;
price = item.price;
return true;
}
quantity = 0;
price = 0;
return false;
}
// 4. Update quantity
public bool UpdateQuantity(string name, int newQuantity)
{
if (newQuantity <= 0)
throw new ArgumentException("Quantity must be positive!");
if (items.ContainsKey(name))
{
var (quantity, price) = items[name];
items[name] = (newQuantity, price);
Console.WriteLine($"🔄 Updated: {name} (Qty: {quantity} → {newQuantity})");
return true;
}
Console.WriteLine($"⚠️ Item '{name}' not found.");
return false;
}
// 5. Get total value
public decimal GetTotalValue()
{
decimal total = 0;
foreach (var kvp in items)
{
total += kvp.Value.quantity * kvp.Value.price;
}
return total;
}
// 6. Display inventory
public void DisplayInventory()
{
if (items.Count == 0)
{
Console.WriteLine("📭 Inventory is empty.");
return;
}
Console.WriteLine($"\n📦 INVENTORY ({Count} items):");
Console.WriteLine($"{"Item",-20} {"Qty",-6} {"Price",-10} {"Value",-10}");
Console.WriteLine($"{"────",-20} {"───",-6} {"─────",-10} {"─────",-10}");
foreach (var kvp in items)
{
string name = kvp.Key;
int qty = kvp.Value.quantity;
decimal price = kvp.Value.price;
decimal value = qty * price;
Console.WriteLine($"{name,-20} {qty,-6} ${price,-9:F2} ${value,-9:F2}");
}
Console.WriteLine($"\n💰 Total Inventory Value: ${GetTotalValue():F2}\n");
}
// 7. Count property
public int Count => items.Count;
}
// Program.cs
class Program
{
static void Main()
{
Console.WriteLine("📦 INVENTORY MANAGEMENT SYSTEM");
Console.WriteLine("═══════════════════════════════════\n");
InventoryManager inventory = new InventoryManager();
// Add items
inventory.AddItem("Laptop", 5, 999.99m);
inventory.AddItem("Mouse", 20, 25.50m);
inventory.AddItem("Keyboard", 15, 45.00m);
inventory.AddItem("Monitor", 3, 299.99m);
Console.WriteLine();
inventory.DisplayInventory();
// Update quantity
inventory.UpdateQuantity("Mouse", 30);
// Find an item
if (inventory.FindItem("Laptop", out int qty, out decimal price))
{
Console.WriteLine($"🔍 Found: Laptop (Qty: {qty}, Price: ${price:F2})");
}
// Remove an item
inventory.RemoveItem("Monitor");
Console.WriteLine();
inventory.DisplayInventory();
Console.WriteLine($"📊 Total items: {inventory.Count}");
Console.WriteLine($"💰 Total value: ${inventory.GetTotalValue():F2}");
}
}