Methods Deep Dive

How to Make Your Classes Do Things

Intermediate 25 min read Lesson 3 of 11

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!

Think of it like this:
  • 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 void if 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
Think of it like: A method is like a recipe. You give it ingredients (parameters), it does something, and gives you a result.

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
}
Example: 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
}
Example: printer.Print("Hello") - it prints, but gives nothing back
void = "empty" in Latin No 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)
Like: Making a photocopy - changing the copy doesn't affect the original
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)
Like: Giving someone your phone - they can change it
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
}
Like: A vending machine - it gives you a drink and tells you if it worked
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!
Flexibility: You can call the method with or without the optional parameter

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
Important: You can only use one 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
Why overloading? It makes your class flexible and easy to use. Users can call the same method name with different inputs.

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

When to use static: Utility methods like 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);
Benefits: Shorter, cleaner, easier to read

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}");
    }
}
What this shows:
  • 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:
  1. AddItem - Add an item with name and quantity
    • Optional price parameter (default 0)
    • Validate that name is not empty
    • Validate quantity is positive
  2. RemoveItem - Remove item by name
    • Returns true if removed
    • Returns false if not found
  3. FindItem - Find item by name
    • Uses out parameter to return quantity
    • Returns true if found
More Requirements:
  1. UpdateQuantity - Update quantity by name
    • New quantity must be positive
    • Returns true if updated
  2. GetTotalValue - Calculate total value of all items
    • Uses price * quantity for each item
  3. DisplayInventory - Show all items with formatting
  4. Count - Read-only property for item count
💡 Use the StudentManager as reference!
Test Your Knowledge - Take Quiz