C# Methods
Reusable blocks of code that perform specific tasks
⚙️ What are Methods?
Methods are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs easier to understand and maintain by breaking complex problems into smaller pieces.
// Simple method example
static void SayHello()
{
Console.WriteLine("Hello, World!");
}
SayHello(); // Call the method
Method Components
Method Declaration
Define method name and type
static void MyMethod()
{
// code here
}
Method Call
Execute the method
MyMethod();
// Runs the code
Return Values
Send data back to caller
static int Add()
{
return 5 + 3;
}
Reusability
Call methods multiple times
MyMethod();
MyMethod();
MyMethod();
🔹 Creating and Calling Methods
Methods are defined with a signature (name, parameters, return type) and a body containing executable statements. You call a method by its name followed by parentheses and any required arguments. For example, GreetUser("Alice"); invokes a previously defined method. Methods promote code reuse and organization, breaking complex tasks into manageable units. They must be declared within a class and can be called from other methods, enabling structured, modular programming that improves readability and maintainability.
class Program
{
// Method definition
static void Greet()
{
Console.WriteLine("Welcome to C# Methods!");
Console.WriteLine("Methods make code reusable.");
}
static void Main(string[] args)
{
// Method calls
Greet(); // First call
Greet(); // Second call
}
}
// Output:
// Welcome to C# Methods!
// Methods make code reusable.
// Welcome to C# Methods!
// Methods make code reusable.
Output:
Welcome to C# Methods! Methods make code reusable. Welcome to C# Methods! Methods make code reusable.
🔹 Methods with Return Values
Methods that return values specify a return type (like int, string) and use the return keyword to send back a result. For instance, int GetTotal(int[] numbers) { return numbers.Sum(); } computes and returns the sum. The caller can store the result in a variable or use it directly in expressions. Return methods are essential for calculations, data retrieval, and transformations, enabling information flow between different parts of the program and supporting functional programming patterns.
class Program
{
// Method that returns an integer
static int GetAge()
{
return 25;
}
// Method that returns a string
static string GetName()
{
return "John";
}
static void Main(string[] args)
{
// Store return values
int age = GetAge();
string name = GetName();
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
// Use return value directly
Console.WriteLine("Next year: " + (GetAge() + 1));
}
}
// Output:
// Name: John
// Age: 25
// Next year: 26
Output:
Name: John Age: 25 Next year: 26
🔹 Void vs Return Methods
void methods perform actions without returning a value, while return methods produce a result for the caller. Use void for operations like logging, updating state, or displaying output. Use return methods when you need to compute or fetch data. For example, void Save(data) saves to a database, whereas Data Load(id) retrieves it. Choosing the right type clarifies intent: void for commands, return types for queries. This distinction supports the Command-Query Separation principle for cleaner design.
Key Differences:
- void: Method performs an action but doesn't return a value
- Return type: Method performs calculation and returns a result
- void: Cannot be used in expressions or assignments
- Return type: Can be stored in variables or used in calculations
class Program
{
// Void method - performs action
static void PrintMessage()
{
Console.WriteLine("This is a void method");
}
// Return method - returns value
static int Calculate()
{
return 10 * 5;
}
static void Main(string[] args)
{
// Void method - just call it
PrintMessage();
// Return method - use the value
int result = Calculate();
Console.WriteLine("Result: " + result);
}
}
// Output:
// This is a void method
// Result: 50
Output:
This is a void method Result: 50
🔹 Multiple Return Statements
Methods can contain multiple return statements, typically within conditional branches, to exit early with different results. For example, in a validation method, you might return true if input is valid, false otherwise. Once a return executes, the method exits immediately, skipping any remaining code. This pattern can simplify logic by handling edge cases upfront. However, excessive returns can reduce readability, so aim for a clear flow—often a single return at the end is preferable for complex methods.
class Program
{
static string CheckAge(int age)
{
if (age >= 18)
{
return "Adult";
}
else if (age >= 13)
{
return "Teenager";
}
else
{
return "Child";
}
}
static void Main(string[] args)
{
Console.WriteLine("Age 25: " + CheckAge(25));
Console.WriteLine("Age 15: " + CheckAge(15));
Console.WriteLine("Age 8: " + CheckAge(8));
}
}
// Output:
// Age 25: Adult
// Age 15: Teenager
// Age 8: Child
Output:
Age 25: Adult Age 15: Teenager Age 8: Child
🔹 Method Naming Conventions
Method names should clearly and concisely describe their function, using verbs or verb phrases. Follow PascalCase for public methods (e.g., CalculateTotal()) and camelCase for private/internal ones. Names like GetUserData(), IsValid(), or ProcessPayment() instantly convey purpose, improving code readability and maintenance. Avoid ambiguous terms like Handle() or DoWork(). Consistent naming across a project is crucial for teamwork and reducing cognitive load during debugging and feature development.
Best Practices:
- PascalCase: Start with uppercase, capitalize each word (CalculateTotal)
- Descriptive: Use clear names that describe what the method does
- Verbs: Start with action words (Get, Set, Calculate, Print, Check)
- Avoid abbreviations: Use full words for clarity
class Program
{
// Good method names
static void DisplayWelcomeMessage()
{
Console.WriteLine("Welcome!");
}
static int CalculateSum(int a, int b)
{
return a + b;
}
static bool IsEven(int number)
{
return number % 2 == 0;
}
static void Main(string[] args)
{
DisplayWelcomeMessage();
int total = CalculateSum(5, 3);
bool even = IsEven(10);
Console.WriteLine("Sum: " + total);
Console.WriteLine("Is 10 even? " + even);
}
}
// Output:
// Welcome!
// Sum: 8
// Is 10 even? True
Output:
Welcome! Sum: 8 Is 10 even? True
🔹 Practical Example: Calculator Methods
A well-structured calculator program demonstrates clean separation of concerns using distinct methods. For instance, Add(a, b), Subtract(a, b), Multiply(a, b), and Divide(a, b) each handle a single operation. A main Calculate() method can call these based on user input. This modular approach makes the code easy to test, debug, and extend—adding a new operation like Power() doesn't disrupt existing logic, showcasing core principles of method design and reusability.
class Program
{
static int Add(int x, int y)
{
return x + y;
}
static int Subtract(int x, int y)
{
return x - y;
}
static int Multiply(int x, int y)
{
return x * y;
}
static void DisplayResult(string operation, int result)
{
Console.WriteLine(operation + " = " + result);
}
static void Main(string[] args)
{
int a = 10, b = 5;
DisplayResult("10 + 5", Add(a, b));
DisplayResult("10 - 5", Subtract(a, b));
DisplayResult("10 * 5", Multiply(a, b));
}
}
// Output:
// 10 + 5 = 15
// 10 - 5 = 5
// 10 * 5 = 50
Output:
10 + 5 = 15 10 - 5 = 5 10 * 5 = 50