Introduction
Think about a program like Microsoft word or a game like Gears of War. Think about how much code goes into creating into creating something that big They are enormous! Especially when compared to the tiny programs we’ve been working on so far.
How do you manage all that code? Where would you look if there was a bug?
As programmers, we’ve learned that the best way to manage a large program is to break it down into smaller, more manageable pieces. This is called Divide and Conquer. In C#, we do this using Methods.
Functions: A standalone tool that exists on it’s own ( common in languages like C++ , Python) Method: A tool that belongs to a class. Since C# is build on classes, almost every “function” you write is technically a Method.
What is a Method? A method is a “container” for a specific task. Instead of writing one long list of instructions, you take a piece of code, give it a name, and store it. You can then “call” that name whenever you need that task done.
Console.WriteLine("Hello World");
Console.WriteLine("Hello World");
Console.WriteLine("Hello World");
Console.WriteLine("Hello World");
Console.WriteLine("Hello World");
/// using funciton.
void SayHello() {
Console.WriteLine("Hello World");
}
SayHello();
SayHello();
SayHello();
SayHello();
SayHello();
Why use them?
- Easy Debugging: If the player in your game isn’t jumping correctly, you don’t look at the whole 1 million lines of code—you just look at the
Jump()method. - Reusability: Don’t reinvent the wheel! Write the logic once, and use it 1,000 times.
- Readability: It turns your code from a wall of text into a clear set of instructions.
Creating a Method
[Access Modifer] [static keyword] [return type] [method name]()
{
[Body]
}
public static void SayHello()
{
Console.WriteLine("Hello");
}
/* we are just skipping the public and static key words */
public: access modifier that determines the visibility of your code, ensure that the method is “open” and can be seen or triggered by other classes and parts of the program. Without this keyword, the method would default to restricted state where only the code inside its immediate container could interact with it
Static : is a memory management keyword that dictates how the method is stored in the computer’s RAM when the program starts. By marking a method as static, you tell the computer to load it into memory immediately as part of the Class itself, which allows you to call the method directly without having to “build” or “instantiate” an object first.
Void: indicates the return type of the method, signaling to the computer that the method will perform an action—such as printing to the console—but will not send a piece of data (like a calculation result) back to the caller.
// Definition.
void CountToTen()
{
for (int i = 1; i <= 10; i++) {
Console.WriteLine(i);
}
}
// calling the function
CountToTen();
Placement of Methods
In C# the order of your code matters for readability. When you start adding methods and custom data types ( like enum) to you program.cs file, you need a clear “Top-To-Bottom” strategy to keep your project organized.
The Standard program Layout While c# is flexible about where you place code, following a consistent structure prevents confusions. Think of your file as having three distinct “zones” that follow the order of execution and complexity.
1. The Action Zone (TOP) This is where your program actually begins. You should place your primary instructions and method calls here. This is the first thing a developers sees when they open your file, so it should clearly show what the program does
2. The Method Zone (MIDDLE/ BOTTOM) Place your method definitions the “how-to” instructions directly below your main actions. Even though C# allows you to mix these among your main statements, keeping them at the bottom ensures they don’t clutter your main logic.
3. The Type Zone (FINAL) If you are creating custom types, such as an Enum these must go at the very end. A new type definition signals to the compiler that the main methods area has finished.
// --- ZONE 1: ACTIONS ---
// These run first
DisplayAMonth();
DisplayAnotherMonth();
// --- ZONE 2: METHODS ---
// These are the "skills" we defined
void DisplayAMonth()
{
Console.WriteLine(Month.January);
}
void DisplayAnotherMonth()
{
Console.WriteLine(Month.July);
}
// --- ZONE 3: TYPES ---
// Definitions like enums go at the very bottom
enum Month { January, February, March, April, May, June, July }
Adding Parameters
Methods without parameters always do the exact same thing. Parameters allow you to send data into method, making it a flexible tool that can produce different results based on the information you provide.
Syntax of Parameter
A parameter is essentially a variable declared inside the method’s parentheses. It acts as a placeholder for the data the method needs to do it’s job.
void CountTo (int number) { }
- The parameter ( int number) : This is a variable name and type. You don’t need to give it a value here; it is “empty” until the method is called.
- The Argument: This is the actual value you pass into the parentheses when you call the method. eg
CountTo(10).
// Definition.
void CountToTen(int number)
{
for (int i = 1; i <= number; i++) {
Console.WriteLine(i);
}
}
// calling the function
CountToTen(10);
Example “Double It” Method This method takes one number and shows you what it looks like when multiplied by 2.
// THE CALL
DoubleNumber(5); // Output: 10
DoubleNumber(12); // Output: 24
// THE DEFINITION
void DoubleNumber(int input)
{
int result = input * 2;
Console.WriteLine(result);
}
Example. “Simple Plus” Method This shows how to send two different numbers into a method. The method waits for both numbers, adds them together, and prints the answer.
// --- THE CALL ---
AddTwoNumbers(10, 5); // Output: 15
AddTwoNumbers(20, 20); // Output: 40
// --- THE DEFINITION ---
static void AddTwoNumbers(int a, int b)
{
int sum = a + b;
Console.WriteLine(sum);
}
Returning from a Method
Until now, our methods have been like a worker who does a job but never speaks back. Returning is how a method “talks back” to the program by giving you a result or a answer.
Swapping void for a Data Type
When you don’t want a result, you use void. When you do want a result you must tell C# exactly what kind of data is coming back (like int, string or bool).
The Rule:
void“i will do the work, but i have nothing to give you”int“i will do the work and give you back a whole number”string“i will do the work and give you back text”
The return keyword
The return statement is the final act of a method. It exits the method and “teleports” the value back to wherever the method was called.
Example simplest Return This method doesn’t just print a number, it hands it to your so you can use it in your code.
// THE CALL
int result = GetLuckyNumber(); // The '7' is stored in 'result'
Console.WriteLine("My number is: " + result);
// THE DEFINITION
int GetLuckyNumber()
{
return 7; // This sends the number 7 back
}
Adding Numbers and returning the sum This is a very common way to use methods, you give it two numbers, and it gives you back the answer.
// THE CALL
int total = Add(5, 10);
Console.WriteLine("The sum is: " + total);
// THE DEFINITION
int Add(int a, int b)
{
int sum = a + b;
return sum; // Handing back the answer
}
Example Every time you want a number from the user, you have to write three lines of code. If you have 10 numbers to ask for, that is 30 lines of messy code!
Console.Write("Enter Age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Year: ");
int year = Convert.ToInt32(Console.ReadLine());
We build a tool once and reuse it. the code is cleaner and easier to read.
// THE CALL:
int age = AskForNumber("Enter Age: ");
int year = AskForNumber("Enter Year: ");
// THE DEFINITION:
int AskForNumber(string message)
{
Console.Write(message);
string input = Console.ReadLine();
return Convert.ToInt32(input); // We hand the finished number back
}
Early Returning
a return statement is an Emergency Exit in a void method, you use it to stop the code from running if a certain condition isn’t met.
// THE CALL
DriveCar(0); // Output: Out of gas! (Stops early)
DriveCar(50); // Output: Driving... Vroom!
void DriveCar(int gasAmount)
{
if (gasAmount <= 0)
{
Console.WriteLine("Out of gas!");
return; // EXIT NOW. The code below will be ignored.
}
// This only runs if we didn't return early
Console.WriteLine("Driving...!");
}
-
Void = The method does a job and disappears.
-
Return Type (int, string, etc.) = The method does a job and hands you a result.
-
The Variable “Catch”: When a method returns something, you must “catch” it in a variable (e.g.,
int x = Method();) or it just falls on the floor and is lost! -
The “Exit” Sign:
returnis the last thing a method does. Once it hits areturn, it teleports back to the Main method immediately.
method overloads ( Not going to work on Top-Level Statements)
overloading is when you give multiple methods the exact same name, but you give them different parameters ( different types or a different number of “slots”)
The computer is smart enough to look at the data you provide and pick the version of the method that matches.
Example: Console.WriteLine()
You have been using overloading since Day 1! Think about how Console.WriteLine works:
- You can put a string inside:
Console.WriteLine("Hello"); - You can put an int inside:
Console.WriteLine(100); - You can put a bool inside:
Console.WriteLine(true);
In the background, C# actually has many different versions of WriteLine. It sees you used a number and says, “Okay, use the Integer version of this method!”
Why do we need it ? ( The simple Reason) Imagine if overloading didn’t exist. You would have to remember a different name for every single type of data:
WriteText("Hello");WriteNumber(10);WriteDecimal(5.5);
Overloading lets us just use Write() for everything. It makes the code much cleaner and easier to remember.
Parameters must be different
The computer ignores the Return Type. It only looks at what is inside the parentheses ( ).
-
Allowed:
void Attack(int power)void Attack(string weaponName)
-
NOT Allowed:
void Attack(int power)int Attack(int power)(The computer gets confused because the “input” looks the same).
Even though we can’t build them inside Main yet, show them what a “Math” class with overloads would look like:
// Version A: Adds two whole numbers
static void Add(int a, int b) {
Console.WriteLine(a + b);
}
// Version B: Adds two decimal numbers
static void Add(double a, double b) {
Console.WriteLine(a + b);
}
// Version C: Adds THREE whole numbers
static void Add(int a, int b, int c) {
Console.WriteLine(a + b + c);
}
- Overloading = Same Name + Different Parameters.
- The Compiler picks the right one based on what you “feed” the method.
- Return types do not matter for overloading.
- It makes code reusable and easier to read.