Methods Basics

Intermediate 30 min read Lesson 10 of 13

What are Methods?

A method is a block of code that performs a specific task. Think of it like a recipe - you give it ingredients (parameters), it follows steps, and gives you a result (return value).

Reusable
Write once, use many times

Organized
Break down complex problems

Testable
Easy to fix and debug

Think of it like this: A method is like a machine that takes input (parameters), processes it, and produces output (return value). You can use the same machine over and over!

Why Are Methods Important?

Benefits
  • Reusability: Write code once, use it everywhere
  • Organization: Break big problems into small pieces
  • Maintainability: Fix one place, fix everywhere
  • Readability: Code that is easy to understand
  • Testing: Test each method individually
  • Teamwork: Different people can work on different methods
Real-World Examples
  • 🏦 Banking: Deposit, Withdraw, CheckBalance
  • 🛒 Shopping: AddToCart, RemoveFromCart, Checkout
  • 📧 Email: SendEmail, ValidateEmail, FormatEmail
  • 📊 Calculator: Add, Subtract, Multiply, Divide
  • 👤 User: Register, Login, UpdateProfile

Method Structure

Every method has a structure that tells C# what it does. Here's the anatomy of a method:

// ===== METHOD STRUCTURE ANATOMY =====
// [Access Modifier] [Static] [Return Type] MethodName(Parameters)
public static int AddNumbers(int a, int b)
{
    // Method body
    int result = a + b;
    return result;
}

// ===== BREAKING IT DOWN =====
// public         → Anyone can call this method
// static         → Belongs to the class, not an object
// int            → Returns an integer
// AddNumbers     → Name of the method (descriptive)
// (int a, int b) → Parameters (input)
// { ... }        → Method body (code)
// return result; → Returns the value
Access

Who can use it

Return

What it gives back

Name

What it's called

Parameters

What it takes

Return Types

The return type tells C# what kind of value the method gives back. If it doesn't return anything, use void.

// ===== VOID - No Return Value =====
public void SayHello(string name)
{
    Console.WriteLine($"Hello, {name}!");
    // No return statement needed
}

// ===== STRING Return =====
public string GetFullName(string first, string last)
{
    return $"{first} {last}";
}

// ===== INT Return =====
public int CalculateAge(DateTime birthDate)
{
    int age = DateTime.Now.Year - birthDate.Year;
    return age;
}

// ===== BOOL Return =====
public bool IsAdult(int age)
{
    return age >= 18;
}

// ===== ARRAY Return =====
public int[] GetNumbers()
{
    return new int[] { 1, 2, 3, 4 };
}
Remember: If your method returns something, you must use the return keyword. If it's void, you don't need to return anything.

Method Parameters (Input)

Parameters are like ingredients - they are the inputs your method needs to do its job.

// ===== BASIC PARAMETERS =====
public void PrintName(string firstName, string lastName)
{
    Console.WriteLine($"{firstName} {lastName}");
}

// ===== DEFAULT (OPTIONAL) PARAMETERS =====
public void Greet(string name, string greeting = "Hello")
{
    Console.WriteLine($"{greeting}, {name}!");
}

Greet("John");           // "Hello, John!"
Greet("Jane", "Hi");      // "Hi, Jane!"

// ===== PARAMS ARRAY (Variable number of arguments) =====
public int SumNumbers(params int[] numbers)
{
    int total = 0;
    foreach (int num in numbers)
    {
        total += num;
    }
    return total;
}

int result1 = SumNumbers(1, 2, 3);        // 6
int result2 = SumNumbers(1, 2, 3, 4, 5);  // 15
Pro Tip: Use default parameters for optional values, and params when you don't know how many arguments you'll get.

Ref and Out Parameters

Normally, methods receive a copy of the data. But sometimes you need to modify the original data or return multiple values.

// ===== REF - Pass by Reference =====
// Changes the original variable
public void Increment(ref int number)
{
    number++;  // Changes the original value
}

int x = 5;
Increment(ref x);
Console.WriteLine(x);  // Output: 6

// ===== OUT - Return Multiple Values =====
// Good for "Try" patterns
public bool TryDivide(int a, int b, out int result)
{
    if (b == 0)
    {
        result = 0;
        return false;  // Failed
    }
    result = a / b;
    return true;   // Success
}

if (TryDivide(10, 2, out int quotient))
{
    Console.WriteLine($"Result: {quotient}");  // Result: 5
}

// ===== REAL-WORLD: Parse with TryParse =====
string input = "123";
if (int.TryParse(input, out int number))
{
    Console.WriteLine($"Success: {number}");
}
else
{
    Console.WriteLine("Invalid number!");
}
ref

Use when you want to modify the original value.

out

Use when you need to return multiple values.

Method Overloading

Overloading means having multiple methods with the same name but different parameters. This makes your code more flexible.

// ===== METHOD OVERLOADING =====
// Different number of parameters
public int Add(int a, int b)
{
    return a + b;
}

public int Add(int a, int b, int c)
{
    return a + b + c;
}

// Different types of parameters
public double Add(double a, double b)
{
    return a + b;
}

// Different order of parameters
public string Add(string a, string b)
{
    return a + b;  // Concatenation
}

// ===== USING THE OVERLOADED METHODS =====
int sum1 = Add(5, 3);          // 8
int sum2 = Add(5, 3, 2);       // 10
double sum3 = Add(5.5, 3.2);    // 8.7
string sum4 = Add("Hello", "World");  // "HelloWorld"
Important: Overloading is determined by the parameters (number, type, order). The return type does NOT affect overloading.

Static vs Instance Methods

Static methods belong to the class itself. Instance methods belong to objects of the class.

// ===== STATIC METHOD =====
// Belongs to the class. Called without creating an object.
public static double CalculateCircleArea(double radius)
{
    return Math.PI * radius * radius;
}

// Usage: No object needed!
double area = Calculator.CalculateCircleArea(5);

// ===== INSTANCE METHOD =====
// Belongs to an object. Needs an instance to call.
public void SetName(string name)
{
    this.Name = name;
}

// Usage: Need to create an object first!
Student student = new Student();
student.SetName("John");

// ===== COMPARISON =====
// Static  → Belongs to class, no object needed
// Instance → Belongs to object, object required
When to use Static
  • Utility functions (Math, Helpers)
  • No need for object state
  • Shared across all objects
When to use Instance
  • Need to access object data
  • Each object has different state
  • Object-specific behavior

Naming Conventions

Good method names are descriptive and follow conventions.

✅ Good Names ❌ Bad Names Why?
CalculateTotal() DoStuff() Describes what it does
GetUserAge() Method1() Clearly states purpose
IsValidEmail() Check() Returns a boolean
SaveCustomer() DoSave() Shows what it saves
GetFullName() Get() Specific about what it gets
Rule of thumb: Method names should be verbs that describe what the method does. Use PascalCase (e.g., CalculateTotal).

Real-World Examples

🏦 Bank Account
public void Deposit(decimal amount)
{
    if (amount <= 0)
        throw new ArgumentException("Amount must be positive");
    Balance += amount;
}

public bool Withdraw(decimal amount)
{
    if (amount > Balance) return false;
    Balance -= amount;
    return true;
}
📊 Weather Converter
public double CelsiusToFahrenheit(double celsius)
{
    return (celsius * 9 / 5) + 32;
}

public double FahrenheitToCelsius(double fahrenheit)
{
    return (fahrenheit - 32) * 5 / 9;
}
🔑 Password Validation
public bool IsValidPassword(string password)
{
    return password.Length >= 8 &&
           password.Any(char.IsUpper) &&
           password.Any(char.IsLower) &&
           password.Any(char.IsDigit);
}
📧 Email Formatter
public string FormatEmail(string name, string domain)
{
    string formatted = name.ToLower().Replace(" ", ".");
    return $"{formatted}@{
    domain
    }
.com";
}

Exercise: Shopping Cart

Task: Create a shopping cart system with methods.

Instructions:
  1. Create a Product class with: Name, Price, Quantity
  2. Create a ShoppingCart class with:
    • AddItem() - Add a product
    • RemoveItem() - Remove a product
    • GetTotal() - Calculate total price
    • ApplyDiscount() - Apply a discount percentage
    • GetItemCount() - Get total number of items
    • ClearCart() - Remove all items
  3. Use overloading for adding items (single item and multiple items)
  4. Use optional parameters for discount
  5. Return bool for success/failure operations
Hints:
  • Use a List<Product> to store items
  • Use foreach to calculate totals
  • Use return true/false for Add/Remove methods
Key Takeaway

Methods are the building blocks of your code:

✅ Write methods that do one thing and do it well
✅ Use meaningful names that describe what they do
✅ Use parameters to pass input
✅ Use return values to get output
✅ Use overloading for flexibility
✅ Use static for utility methods
✅ Use ref/out when needed
✅ Keep methods short and focused

Test Your Knowledge - Take Quiz