Methods: Reusable Blocks of Code
7 min read
π Introduction: The "Copy-Paste" Nightmare
Imagine you are writing a program to simulate a morning routine. You write 10 lines of code to "Make Coffee." Then, you need to make coffee again in the afternoon. What do you do?
The Novice Approach: Copy those 10 lines and paste them later in the file.
The Problem: Suddenly, you realize you forgot to add sugar in your code. Now you have to find every place you pasted that code and fix it. If you pasted it 50 times, you have a long, boring night ahead of you. π«
The Solution: Methods.
A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, a method is executed in the context of a class or struct.
Think of a method like a spell in a wizard's book. You define the spell once (write the code), and then you can cast it (call the method) as many times as you want by just saying its name. πͺ
1. Defining and Calling Methods
Before we run, we must walk. Before we code complex systems, we must understand structure.
The Definition
In C#, a method is defined inside a class (or a struct). A basic method definition looks like this:
// [Access Modifier] [Return Type] [Method Name] ([Parameters])
public void SayHello ()
{
// Method Body
Console.WriteLine("Hello, World!");
}- Access Modifier (
public): Who can see this? (Public means everyone). - Return Type (
void): What does this give back? (voidmeans nothing). - Method Name (
SayHello): The name we call it by. - Parentheses
(): Where data goes in (empty for now). - Body
{ ... }: The actual code to run.
The Problem: Ghost Code π»
You wrote the method above. You hit "Run." Nothing happens. Why?
Fact: Writing a method creates the potential for action. It doesn't actually run until you Call (invoke) it. Itβs like buying a treadmill but never stepping on it. It sits there, looking fit, doing nothing.
The Solution: Calling the Method
To execute the method, you use its name followed by parentheses.
class Program
{
static void Main()
{
Console.WriteLine("System booting...");
// CALLING the method here:
PrintWarning();
PrintWarning(); // Reusability! Called it twice.
Console.WriteLine("System shutting down.");
}
// DEFINING the method here:
static void PrintWarning()
{
Console.WriteLine("β οΈ Warning: Reactor core is hot!");
}
}π‘ Under the Hood:
When you call a method, the CPU pauses the current execution (in Main), creates a "stack frame" in memory for the new method, runs the code inside it, and when finished, destroys that frame and jumps right back to where it left off in Main.
2. Parameters and Arguments: Passing Data In π
The Problem
Our PrintWarning method is inflexible. It always prints the exact same text. What if we want to warn about different things, like "Low Battery" or "Godzilla Approaching"? We don't want to write a separate method for every possible warning.
The Solution: Parameters
Parameters act as variables inside the method definition. They act as placeholders for data that will be sent in later.
- Parameter: The variable defined in the method signature (e.g.,
string message). - Argument: The actual data passed when calling the method (e.g.,
"Godzilla is here").
Syntax
// 'message' and 'severityLevel' are PARAMETERS
static void ShowAlert(string message, int severityLevel)
{
Console.WriteLine($"Alert Level {severityLevel}: {message}");
}
// Usage in Main:
// "Intruder" and 5 are ARGUMENTS
ShowAlert("Intruder detected", 5);
ShowAlert("Coffee is ready", 1);Industry Standard Tip π:
Naming matters!
- PascalCase for Method Names (
CalculateTax). - camelCase for Parameters (
totalAmount).
Common Mistake:
Trying to access the message variable outside of the ShowAlert method.
Concept: Scope. Parameters only exist inside the method they are defined in. Once the method finishes, those variables are poofed out of existence.
3. Return Types: Getting Data Out π€
The Problem
So far, our methods just print to the console. In the real world, methods usually calculate data and give it back so the program can use it. Imagine a calculator that computes 2 + 2 but refuses to show you the number, instead just whispering it to itself. Useless.
The Solution: Return Values
Instead of void (which means empty/vacuum), we specify a data type (like int, string, bool, double).
// Changed 'void' to 'int'
static int AddNumbers(int a, int b)
{
int result = a + b;
return result; // We must use the 'return' keyword
}Capturing the Result
When a method returns a value, the method call itself evaluates to that value. You can store it in a variable.
int mySalary = 5000;
int bonus = 1000;
// The method turns into the value '6000' here
int total = AddNumbers(mySalary, bonus);
Console.WriteLine($"Total: {total}");Fun Fact π:
Once the code hits the return keyword, the method stops immediately. It exits the party. Any code written after the return statement is called "unreachable code" and the compiler will yell at you (politely, usually).
static bool IsPizzaTasty()
{
return true;
Console.WriteLine("This will never print."); // π Dead code
}4. Method Overloading: Same Name, Different Signatures π―ββοΈ
The Problem
You want to create a method called Add.
Sometimes you want to add two integers: Add(5, 10).
Sometimes you want to add three integers: Add(5, 10, 20).
Sometimes you want to add decimals: Add(5.5, 2.2).
In older languages (like C), you'd have to name them AddTwoInts, AddThreeInts, AddDoubles. This is ugly and hard to remember.
The Solution: Overloading
C# allows you to have multiple methods with the same name, as long as their signature is different.
What is a Signature?
Signature = Method Name + Parameter List (Types and Order).
Note: The return type is NOT part of the signature for overloading purposes.
class Calculator
{
// Option 1: Two integers
static int Add(int a, int b)
{
return a + b;
}
// Option 2: Three integers (Overloaded)
static int Add(int a, int b, int c)
{
return a + b + c;
}
// Option 3: Doubles (Overloaded)
static double Add(double a, double b)
{
return a + b;
}
}
// Usage:
// C# is smart enough to pick the right one based on the arguments!
Add(1, 2); // Calls Option 1
Add(1, 2, 3); // Calls Option 2
Add(1.5, 2.5); // Calls Option 3Industry Practice:
Overloading is widely used in the C# standard library. For example, Console.WriteLine() is overloaded heavily. You can pass it an int, a string, a bool, or an object, and it just works.
π§ͺ Practical Example: The RPG Character Generator
Let's combine everything into a real-world scenario (well, a gaming scenario).
using System;
class Program
{
static void Main()
{
// 1. Simple Void Method
PrintWelcomeBanner();
// 2. Method with Return Value and Parameters
int heroLevel = CalculateLevel(500); // 500 XP
// 3. Method Overloading
string warrior = CreateCharacter("Conan");
string mage = CreateCharacter("Gandalf", "Wizard");
Console.WriteLine($"Hero Level: {heroLevel}");
Console.WriteLine(warrior);
Console.WriteLine(mage);
}
static void PrintWelcomeBanner()
{
Console.WriteLine("βοΈ --- NEW GAME STARTED --- βοΈ");
}
static int CalculateLevel(int xp)
{
// Simple logic: Level = XP / 100
return xp / 100;
}
// Overload 1: Default class is "Peasant"
static string CreateCharacter(string name)
{
return $"Player: {name} | Class: Peasant";
}
// Overload 2: Specify class
static string CreateCharacter(string name, string characterClass)
{
return $"Player: {name} | Class: {characterClass}";
}
}π§ Things to Remember (The "Gotchas")
- DRY Principle: Don't Repeat Yourself. If you paste the same code twice, put it in a method.
- Single Responsibility Principle (SRP): A method should do one thing. A method named
LoginUserAndCalculateTaxAndSendEmail()is a bad method. Break it into three smaller methods. - Static: You noticed we used
staticin the examples. For now, just know thatstaticmeans the method belongs to the class itself, not a specific instance of an object. Since we are running insideProgram.Main(which is static), our helpers usually need to be static too until we learn Object-Oriented Programming (OOP).
π References & Further Reading
Challenge
C# RPG Inventory Utility Class
You are tasked with creating a static utility class in C# to manage common inventory-related operations for an RPG. The class will be named InventoryManager.
Your goal is to implement several methods adhering to specific signatures and functionalities, including demonstrating method overloading.
Requirements:
Create a
public staticmethod namedCalculateTotalWeight. This method must accept anintrepresenting item quantity and adoublerepresenting the weight of a single item. It should return the total weight as adouble.Create a
public staticmethod namedFormatItemInfo. It must accept astringfor the item's name and anintfor its quantity. It should return a formatted string in the exact pattern:"<ItemName> (x<Quantity>)". For example, if called with"Sword"and5, it should return"Sword (x5)".Implement method overloading by creating three distinct
public staticmethods, all namedGenerateLootMessage:- The first overload must accept a single
stringparameter for an item's name and return astringmessage:"You found a <ItemName>!". - The second overload must accept a
stringfor the item name and anintfor the quantity. It should return the message:"You found <Quantity> of <ItemName>!". - The third overload must accept a
stringfor the item name, anintfor the quantity, and astringfor a player's name. It should return:"<PlayerName> has acquired <Quantity> of <ItemName>!".
- The first overload must accept a single
Finally, define a
private statichelper method namedLogTransaction. This method should have avoidreturn type and accept a singlestringparameter for the log message. Its body can be empty. This is to practice defining methods with different access modifiers.
Expected result
Your final code should contain the InventoryManager static class with the following five methods correctly defined inside it:
public static double CalculateTotalWeight(int itemQuantity, double itemWeight): This method should contain a return statement that correctly calculates and returns the product of the two parameters.public static string FormatItemInfo(string itemName, int quantity): This method should return a string formatted exactly as$"{itemName} (x{quantity})"or an equivalent string concatenation.The three overloaded
public static string GenerateLootMessagemethods, each with the specified parameter lists (string), (string,int), and (string,int,string), returning the correctly formatted string for each case.A
private static void LogTransaction(string message)method with an empty body{}.