Methods are one of the most important concepts in programming. They let you group code into reusable blocks. Instead of writing the same code over and over, you write it once in a method and call it whenever you need it.
Your First Method
void GreetUser()
{
Console.WriteLine("Hello there!");
Console.WriteLine("Welcome to our app.");
}
// Calling the method
GreetUser();
GreetUser(); // You can call it as many times as you want
The word void means this method does not return any value. The method name
is GreetUser, and the parentheses after it are where you would put parameters
(we will cover those soon). The code inside the curly braces is what runs when you
call the method.
Methods That Return Values
Sometimes you want a method to calculate something and give you back the result. Instead
of void, you specify the return type:
int Add(int a, int b)
{
return a + b;
}
string GetGreeting(string name)
{
return $"Hello, {name}!";
}
// Using the methods
int sum = Add(5, 3);
Console.WriteLine(sum); // 8
string greeting = GetGreeting("Amina");
Console.WriteLine(greeting); // Hello, Amina!
The return keyword sends a value back to wherever the method was called.
Once C# hits a return statement, it immediately exits the method. Any code
after return will never run.
Method Naming Conventions
In C#, method names use PascalCase โ each word starts with a capital letter:
void CalculateTotal() { } // Good
void calculateTotal() { } // Bad โ should be PascalCase
void CALCULATETOTAL() { } // Very bad
Choose names that describe what the method does. A good method name tells you exactly what to expect without having to read the code inside.
Keeping Methods Small
A good practice is to keep each method focused on one thing. If a method is doing multiple unrelated things, it is probably too big. Split it into smaller methods.
// Bad โ doing too many things
void ProcessOrder()
{
// 50 lines of validation
// 50 lines of calculation
// 50 lines of database work
}
// Good โ each method has one job
void ValidateOrder() { /* ... */ }
void CalculateTotal() { /* ... */ }
void SaveToDatabase() { /* ... */ }
This makes your code easier to read, test, and maintain. Trust me, your future self will thank you for this.