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
csharp1static void MethodName()2{3 // Code to execute4}
- 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
csharp1// Define the method2static void SayHello()3{4 Console.WriteLine("Hello, World!");5}67// Call the method (in Main or top-level code)8SayHello();9SayHello(); // Can call multiple times10SayHello();
Output
1Hello, World!2Hello, World!3Hello, World!
Where to Define Methods
In modern C# with top-level statements:
csharp1// Top-level code runs first2Console.WriteLine("Program started");3Greet();4Console.WriteLine("Program ended");56// Methods defined after top-level code7static void Greet()8{9 Console.WriteLine("Welcome!");10}
In traditional C# with a Program class:
csharp1class Program2{3 static void Main()4 {5 Greet();6 }78 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
csharp1// Good names2static void PrintMenu() { }3static void CalculateTotal() { }4static void ValidateInput() { }5static void SaveToFile() { }67// Poor names8static void DoStuff() { }9static void xyz() { }10static void Method1() { }
Methods with Multiple Statements
csharp1static void PrintHeader()2{3 Console.WriteLine("═══════════════════════════");4 Console.WriteLine(" MY APPLICATION ");5 Console.WriteLine("═══════════════════════════");6}78static void PrintSeparator()9{10 Console.WriteLine("---------------------------");11}1213// Usage14PrintHeader();15Console.WriteLine("Content goes here");16PrintSeparator();17Console.WriteLine("More content");18PrintSeparator();
Benefits of Methods
1. Code Reuse
csharp1// Without methods (repetitive)2Console.WriteLine("╔════════════════════╗");3Console.WriteLine("║ Processing... ║");4Console.WriteLine("╚════════════════════╝");56// ... later in code ...78Console.WriteLine("╔════════════════════╗");9Console.WriteLine("║ Saving... ║");10Console.WriteLine("╚════════════════════╝");1112// With methods (reusable)13static void ShowBox(string message)14{15 Console.WriteLine("╔════════════════════╗");16 Console.WriteLine($"║ {message,-18} ║");17 Console.WriteLine("╚════════════════════╝");18}1920ShowBox("Processing...");21ShowBox("Saving...");
2. Better Organization
csharp1// Main program flow is clear2DisplayWelcome();3int choice = GetMenuChoice();4ProcessChoice(choice);5DisplayGoodbye();67// Details are in separate methods8static void DisplayWelcome()9{10 Console.WriteLine("Welcome to the app!");11}1213static int GetMenuChoice()14{15 // ... implementation ...16 return 1;17}1819static void ProcessChoice(int choice)20{21 // ... implementation ...22}2324static 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:
csharp1static void MethodA()2{3 int x = 10; // x only exists in MethodA4 Console.WriteLine(x);5}67static void MethodB()8{9 // Console.WriteLine(x); // Error! x doesn't exist here10 int y = 20; // y only exists in MethodB11}
Local Variables
csharp1static void CalculateArea()2{3 int width = 10; // Local variable4 int height = 5; // Local variable5 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:
csharp1static void RunProgram()2{3 Initialize();4 DoMainWork();5 Cleanup();6}78static void Initialize()9{10 Console.WriteLine("Initializing...");11}1213static void DoMainWork()14{15 Console.WriteLine("Working...");16 DoSubTask(); // Calling another method17}1819static void DoSubTask()20{21 Console.WriteLine("Doing subtask...");22}2324static void Cleanup()25{26 Console.WriteLine("Cleaning up...");27}2829// Start30RunProgram();
Practical Example
csharp1// Main program2PrintHeader();3ShowMainMenu();4PrintFooter();56// Methods7static void PrintHeader()8{9 Console.Clear();10 Console.WriteLine("╔═══════════════════════════════════════╗");11 Console.WriteLine("║ EMPLOYEE MANAGEMENT SYSTEM ║");12 Console.WriteLine("╠═══════════════════════════════════════╣");13}1415static 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}2425static 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.