Methods

Loading concept...

🎯 C# Methods: Your Code’s Little Helpers

Imagine you have a magic toy box. Inside are special helpers that do one job really well. You call them when you need them, and they get the job done! In C#, these helpers are called Methods.


🧸 The Big Picture: What Are Methods?

Think of methods like recipe cards in a kitchen.

  • You have a recipe card for “Make a Sandwich”
  • Every time you’re hungry, you follow that card
  • You don’t write new instructions each time!

Methods = Reusable instructions your computer follows.

void MakeSandwich()
{
    Console.WriteLine("Add bread");
    Console.WriteLine("Add filling");
    Console.WriteLine("Done!");
}

Call it anytime:

MakeSandwich();  // Your helper does the work!

📦 Method Fundamentals

Every method has a structure — like how every house has a door, walls, and a roof.

graph TD A[Return Type] --> B[Method Name] B --> C[Parameters] C --> D[Method Body]

The Four Parts:

Part What It Does Example
Return Type What the helper gives back int, string, void
Name The helper’s name AddNumbers
Parameters What you give the helper (int a, int b)
Body The work it does { return a + b; }

Complete Example:

int AddNumbers(int a, int b)
{
    return a + b;
}

🎈 Think of it like ordering pizza:

  • Return type = What you get back (pizza!)
  • Name = “Order Pizza”
  • Parameters = Toppings you choose
  • Body = Kitchen makes your pizza

🎁 Method Parameters

Parameters are like giving your helper the tools they need.

If you ask someone to paint, you give them:

  • The color (what color?)
  • The wall (which wall?)
void Paint(string color, string wall)
{
    Console.WriteLine(quot;Painting {wall} with {color}");
}

// Use it:
Paint("blue", "bedroom wall");

Multiple Parameters:

void Greet(string name, int age)
{
    Console.WriteLine(quot;Hi {name}! You are {age}.");
}

Greet("Alex", 8);  // Hi Alex! You are 8.

🔧 Parameter Modifiers

Sometimes you want your helper to change things or handle missing info. That’s where modifiers come in!

The Four Magical Modifiers:

graph TD A[Parameter Modifiers] --> B[ref - Change Original] A --> C[out - Must Return Something] A --> D[in - Read Only] A --> E[params - Many Items]

1. ref - Change the Original

Like lending your toy and getting it back modified:

void DoubleIt(ref int number)
{
    number = number * 2;
}

int myNumber = 5;
DoubleIt(ref myNumber);
// myNumber is now 10!

2. out - Promise to Give Back

The method must put something in this box:

void GetSecret(out string secret)
{
    secret = "The cake is delicious!";
}

GetSecret(out string mySecret);
// mySecret = "The cake is delicious!"

3. in - Look But Don’t Touch

Read-only! Can’t change it:

void ShowNumber(in int value)
{
    Console.WriteLine(value);
    // value = 10; ❌ Not allowed!
}

4. params - Bring as Many as You Want

Like a bag that holds any number of items:

void AddAll(params int[] numbers)
{
    int sum = 0;
    foreach(int n in numbers)
        sum += n;
    Console.WriteLine(sum);
}

AddAll(1, 2, 3);      // 6
AddAll(5, 10, 15, 20); // 50

🔄 Pass by Value vs Reference

This is super important! Let’s use a story.

📝 Pass by Value (The Copy Machine)

Imagine you have a drawing. You make a photocopy and give the copy away.

  • They can scribble on the copy
  • Your original stays safe!
void Change(int x)
{
    x = 100;  // Only changes the copy
}

int original = 5;
Change(original);
// original is still 5! ✅

🔗 Pass by Reference (The Actual Drawing)

Now you give your actual drawing (not a copy).

  • They draw on it
  • Your drawing changes too!
void Change(ref int x)
{
    x = 100;  // Changes the original!
}

int original = 5;
Change(ref original);
// original is now 100!
Type What Happens Your Original
Value Copy is changed Safe ✅
Reference Original is changed Modified ⚠️

🎭 Method Overloading

What if your helper could do slightly different jobs with the same name?

Like how “Play” can mean:

  • Play music 🎵
  • Play a game 🎮
  • Play with friends 👫

Same name, different skills!

// Play with a song name
void Play(string song)
{
    Console.WriteLine(quot;Playing {song}");
}

// Play for a number of minutes
void Play(int minutes)
{
    Console.WriteLine(quot;Playing for {minutes} min");
}

// Play a specific song for specific time
void Play(string song, int minutes)
{
    Console.WriteLine(quot;Playing {song} for {minutes} min");
}

C# picks the right one based on what you give it:

Play("Happy Song");        // First version
Play(30);                  // Second version
Play("Happy Song", 5);     // Third version

🌟 Rule: Same name, but different parameters!


🎯 Optional and Named Parameters

Optional Parameters

Like ordering a burger:

  • “I want a burger” (basic)
  • “I want a burger with extra cheese” (optional add-on)
void OrderFood(string item, bool extraCheese = false)
{
    if(extraCheese)
        Console.WriteLine(quot;{item} with extra cheese!");
    else
        Console.WriteLine(item);
}

OrderFood("Burger");              // Burger
OrderFood("Burger", true);        // Burger with extra cheese!

📌 Optional parameters go at the end!

Named Parameters

Sometimes you want to be extra clear:

void CreateProfile(string name, int age, string city)
{
    Console.WriteLine(quot;{name}, {age}, from {city}");
}

// Regular way:
CreateProfile("Sam", 10, "Paris");

// Named way (clearer!):
CreateProfile(name: "Sam", city: "Paris", age: 10);

🎈 Named parameters let you skip order and be super clear!


🏠 Local Functions

A helper inside a helper! Like having a tiny assistant that only works in one room.

void MainJob()
{
    // This helper only exists here!
    void SmallTask()
    {
        Console.WriteLine("Doing small task...");
    }

    SmallTask();  // Use it here
    Console.WriteLine("Main job done!");
}

// SmallTask(); ❌ Can't use outside!

Why Use Them?

  1. Organization - Keep related code together
  2. Safety - No one else can accidentally use it
  3. Clean Code - Main method stays tidy
int Calculate(int[] numbers)
{
    // Local helper to validate
    bool IsValid(int n) => n > 0;

    int sum = 0;
    foreach(int n in numbers)
    {
        if(IsValid(n))
            sum += n;
    }
    return sum;
}

⚡ Expression-Bodied Members

Short methods deserve short code!

If your method does just one thing, why write so much?

Before (Old Way):

int Double(int x)
{
    return x * 2;
}

After (Expression Body):

int Double(int x) => x * 2;

The => arrow says: “This method just returns this!”

More Examples:

// Simple return
string Greet(string name) => quot;Hello, {name}!";

// Property (like a read-only value)
string FullName => quot;{FirstName} {LastName}";

// Void method (does something)
void SayHi() => Console.WriteLine("Hi!");

When to Use:

Use Expression Body When… Use Regular Body When…
One line of code Multiple lines
Simple return Complex logic
Quick operations Loops, conditions

🎪 Putting It All Together

Let’s build a Game Score Tracker using everything!

class ScoreTracker
{
    // Expression-bodied property
    public int HighScore => scores.Max();

    private List<int> scores = new();

    // Method overloading
    public void AddScore(int score)
        => scores.Add(score);

    public void AddScore(params int[] newScores)
        => scores.AddRange(newScores);

    // Optional + named parameters
    public void ShowScores(
        bool sorted = false,
        string title = "Scores")
    {
        Console.WriteLine(title);

        // Local function
        void PrintScore(int s)
            => Console.WriteLine(quot;  • {s}");

        var list = sorted
            ? scores.OrderBy(s => s)
            : scores;

        foreach(var s in list)
            PrintScore(s);
    }

    // ref parameter
    public void DoubleHighest(ref int bonus)
    {
        bonus = HighScore * 2;
    }
}

Using it:

var tracker = new ScoreTracker();
tracker.AddScore(100);
tracker.AddScore(50, 75, 200);
tracker.ShowScores(sorted: true, title: "My Scores");

🌈 Quick Reference

Concept One-Liner
Method Reusable block of code
Parameters Inputs to the method
ref Change original value
out Must return a value
in Read-only parameter
params Variable number of inputs
Overloading Same name, different parameters
Optional Has default value
Named Specify by name
Local Function Method inside method
Expression Body Short => syntax

🚀 You Did It!

Methods are your code’s little helpers. They:

  • ✅ Make code reusable
  • ✅ Keep things organized
  • ✅ Make programs easier to understand
  • ✅ Let you do powerful things simply

Remember the magic toy box! Each method is a helper waiting to be called. Now go create your own helpers! 🎉

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.