12 minlesson

Defining Methods

Defining Methods

Methods are reusable blocks of code that perform specific tasks. They help organize your code, reduce duplication, and make programs easier to understand.

What is a Method?

A method is a named block of code that:

  • Performs a specific task
  • Can accept input (parameters)
  • Can return a result
  • Can be called (invoked) from other code

You've already used methods like Console.WriteLine() and int.Parse().

Basic Method Syntax

csharp
1static void MethodName()
2{
3 // Code to execute
4}
  • static: The method belongs to the class (explained later with OOP)
  • void: The method doesn't return a value
  • MethodName: The name you give the method (PascalCase convention)
  • (): Parameter list (empty if no parameters)
  • {}: The method body

Your First Method

csharp
1// Define the method
2static void SayHello()
3{
4 Console.WriteLine("Hello, World!");
5}
6
7// Call the method (in Main or top-level code)
8SayHello();
9SayHello(); // Can call multiple times
10SayHello();

Output

1Hello, World!
2Hello, World!
3Hello, World!

Where to Define Methods

In modern C# with top-level statements:

csharp
1// Top-level code runs first
2Console.WriteLine("Program started");
3Greet();
4Console.WriteLine("Program ended");
5
6// Methods defined after top-level code
7static void Greet()
8{
9 Console.WriteLine("Welcome!");
10}

In traditional C# with a Program class:

csharp
1class Program
2{
3 static void Main()
4 {
5 Greet();
6 }
7
8 static void Greet()
9 {
10 Console.WriteLine("Welcome!");
11 }
12}

Naming Conventions

  • Use PascalCase for method names
  • Use verbs that describe what the method does
  • Be descriptive but concise
csharp
1// Good names
2static void PrintMenu() { }
3static void CalculateTotal() { }
4static void ValidateInput() { }
5static void SaveToFile() { }
6
7// Poor names
8static void DoStuff() { }
9static void xyz() { }
10static void Method1() { }

Methods with Multiple Statements

csharp
1static void PrintHeader()
2{
3 Console.WriteLine("═══════════════════════════");
4 Console.WriteLine(" MY APPLICATION ");
5 Console.WriteLine("═══════════════════════════");
6}
7
8static void PrintSeparator()
9{
10 Console.WriteLine("---------------------------");
11}
12
13// Usage
14PrintHeader();
15Console.WriteLine("Content goes here");
16PrintSeparator();
17Console.WriteLine("More content");
18PrintSeparator();

Benefits of Methods

1. Code Reuse

csharp
1// Without methods (repetitive)
2Console.WriteLine("╔════════════════════╗");
3Console.WriteLine("║ Processing... ║");
4Console.WriteLine("╚════════════════════╝");
5
6// ... later in code ...
7
8Console.WriteLine("╔════════════════════╗");
9Console.WriteLine("║ Saving... ║");
10Console.WriteLine("╚════════════════════╝");
11
12// With methods (reusable)
13static void ShowBox(string message)
14{
15 Console.WriteLine("╔════════════════════╗");
16 Console.WriteLine($"║ {message,-18} ║");
17 Console.WriteLine("╚════════════════════╝");
18}
19
20ShowBox("Processing...");
21ShowBox("Saving...");

2. Better Organization

csharp
1// Main program flow is clear
2DisplayWelcome();
3int choice = GetMenuChoice();
4ProcessChoice(choice);
5DisplayGoodbye();
6
7// Details are in separate methods
8static void DisplayWelcome()
9{
10 Console.WriteLine("Welcome to the app!");
11}
12
13static int GetMenuChoice()
14{
15 // ... implementation ...
16 return 1;
17}
18
19static void ProcessChoice(int choice)
20{
21 // ... implementation ...
22}
23
24static void DisplayGoodbye()
25{
26 Console.WriteLine("Goodbye!");
27}

3. Easier Testing and Debugging

When code is in methods, you can:

  • Test each method independently
  • Identify where bugs occur
  • Fix issues in one place

Variable Scope

Variables declared inside a method only exist within that method:

csharp
1static void MethodA()
2{
3 int x = 10; // x only exists in MethodA
4 Console.WriteLine(x);
5}
6
7static void MethodB()
8{
9 // Console.WriteLine(x); // Error! x doesn't exist here
10 int y = 20; // y only exists in MethodB
11}

Local Variables

csharp
1static void CalculateArea()
2{
3 int width = 10; // Local variable
4 int height = 5; // Local variable
5 int area = width * height;
6 Console.WriteLine($"Area: {area}");
7}
8// width, height, and area don't exist outside this method

Calling Methods Within Methods

Methods can call other methods:

csharp
1static void RunProgram()
2{
3 Initialize();
4 DoMainWork();
5 Cleanup();
6}
7
8static void Initialize()
9{
10 Console.WriteLine("Initializing...");
11}
12
13static void DoMainWork()
14{
15 Console.WriteLine("Working...");
16 DoSubTask(); // Calling another method
17}
18
19static void DoSubTask()
20{
21 Console.WriteLine("Doing subtask...");
22}
23
24static void Cleanup()
25{
26 Console.WriteLine("Cleaning up...");
27}
28
29// Start
30RunProgram();

Practical Example

csharp
1// Main program
2PrintHeader();
3ShowMainMenu();
4PrintFooter();
5
6// Methods
7static void PrintHeader()
8{
9 Console.Clear();
10 Console.WriteLine("╔═══════════════════════════════════════╗");
11 Console.WriteLine("║ EMPLOYEE MANAGEMENT SYSTEM ║");
12 Console.WriteLine("╠═══════════════════════════════════════╣");
13}
14
15static void ShowMainMenu()
16{
17 Console.WriteLine("║ 1. View Employees ║");
18 Console.WriteLine("║ 2. Add Employee ║");
19 Console.WriteLine("║ 3. Search Employee ║");
20 Console.WriteLine("║ 4. Exit ║");
21 Console.WriteLine("╠═══════════════════════════════════════╣");
22 Console.Write("║ Choose an option: ");
23}
24
25static void PrintFooter()
26{
27 Console.WriteLine();
28 Console.WriteLine("╚═══════════════════════════════════════╝");
29}

Summary

In this lesson, you learned:

  • Methods are named, reusable blocks of code
  • Basic syntax: static void MethodName() { }
  • Methods improve code organization and reduce duplication
  • Variables inside methods are local to that method
  • Methods can call other methods

Next, we'll learn how to pass data to methods using parameters.