Methods
A method is a named, reusable block of code. Instead of copying the same five lines everywhere you need that logic, you write it once, give it a name, and call that name whenever you need the result — and if the logic ever needs to change, there's exactly one place to change it.
Defining and calling a method
A method declaration states the type of value it hands back, a name, and the parameters it accepts in parentheses. return sends the result out and immediately ends the method:
static int Square(int number)
{
return number * number;
}
Console.WriteLine(Square(4));
Console.WriteLine(Square(7));
16 49
number is a parameter — a name that stands in for whatever value gets passed in when the method is actually called. 4 and 7 are the arguments: the real values supplied at each call site.
void methods and multiple parameters
Not every method needs to hand a value back. A method that just performs an action — printing a receipt line, say — is declared void, and has no return statement carrying a value:
static void PrintReceipt(string item, double price)
{
Console.WriteLine($"{item}: ${price}");
}
PrintReceipt("Coffee", 3.50);
PrintReceipt("Bagel", 2.25);
Coffee: $3.5 Bagel: $2.25
Notice 3.50 printed as 3.5 — a trailing zero after the decimal point doesn't change the value, so C#'s default number formatting drops it.
Overloading — same name, different parameters
C# lets you define several methods with the same name as long as their parameter lists are different enough for the compiler to tell them apart. This is useful when an operation makes sense with more than one shape of input:
static double CalculateArea(double side)
{
return side * side;
}
static double CalculateArea(double length, double width)
{
return length * width;
}
Console.WriteLine(CalculateArea(4));
Console.WriteLine(CalculateArea(4, 6));
16 24
The compiler picks which version to run based on how many arguments you pass — one number gets you the square-shape version, two gets you the rectangle version. It's still one clear method name to remember, not two awkwardly-named variants like CalculateSquareArea and CalculateRectangleArea.
Optional parameters
Giving a parameter a default value makes it optional — callers can leave it out entirely, and the default kicks in:
static string FormatPrice(double amount, string currency = "USD") { return $"{amount} {currency}"; } Console.WriteLine(FormatPrice(19.99)); Console.WriteLine(FormatPrice(19.99, "EUR"));
19.99 USD 19.99 EUR