- Define a method with parameters and call it
- Return a result with
returnand explain how this differs fromvoidmethods - Use optional parameters and named arguments
- Tell passing by value apart from passing with
refandout
You calculate a discounted price in five places in your program, copying the same three lines each time. Then you find a mistake in the formula — and now you have to fix it in five places! Methods solve this problem: the code is written once, gets a name and can be called as often as you like. Console.WriteLine, int.Parse and string.Join are methods you already know — now you will write your own.
Defining and calling a method
A method header starts with the return type, then the name, then the parameters with their types in parentheses. void means the method returns nothing. In a program written with top-level statements, methods usually go at the end of the file, but you can still call them from above. Method names start with a capital letter: Greet, CalculateTotal.
Greet("Aysel");
Greet("Murad");
void Greet(string name)
{
Console.WriteLine($"Salam, {name}!");
}Salam, Aysel! Salam, Murad!
A parameter is the variable declared in the method header (string name). An argument is the actual value passed to that parameter when the method is called ("Aysel").
return: giving back a result
If a method returns a result, write the result's type instead of void and use return in the body. return stops the method and sends the value back to where it was called. A method whose body is a single expression can be written briefly with the => arrow.
double area = RectangleArea(4, 3.5);
Console.WriteLine($"Room area: {area}");
Console.WriteLine(IsEven(10));
Console.WriteLine(CelsiusToFahrenheit(25));
double RectangleArea(double width, double height)
{
return width * height;
}
bool IsEven(int n) => n % 2 == 0;
double CelsiusToFahrenheit(double c) => c * 9 / 5 + 32;Room area: 14 True 77
Optional parameters and named arguments
A parameter can have a default value: if the argument is left out in the call, that value is used. Such parameters go at the end of the list. Arguments can also be passed by name — discount: 10 — so their order does not matter and the meaning of the call is clear at once.
Console.WriteLine(FinalPrice(80));
Console.WriteLine(FinalPrice(80, 25));
Console.WriteLine(FinalPrice(discount: 10, price: 50));
PrintTicket("Leyla");
PrintTicket("Elvin", seats: 3);
decimal FinalPrice(decimal price, int discount = 0)
{
return price - price * discount / 100;
}
void PrintTicket(string name, string city = "Baku", int seats = 1)
{
Console.WriteLine($"{name}: {seats} seat(s) in {city}");
}80 60 45 Leyla: 1 seat(s) in Baku Elvin: 3 seat(s) in Baku
seats: 3 is passed by name, the city parameter could be skipped.Several results: tuples, ref and out
A method can return several values at once as a tuple: the return type is written in parentheses, for example (int Min, int Max). When calling it, you can split the tuple straight into separate variables:
int[] temperatures = [12, 5, 27, 9];
var (low, high) = MinMax(temperatures);
Console.WriteLine($"Min: {low}, max: {high}");
(int Min, int Max) MinMax(int[] numbers)
{
int min = numbers[0];
int max = numbers[0];
foreach (int n in numbers)
{
if (n < min) min = n;
if (n > max) max = n;
}
return (min, max);
}Min: 5, max: 27
By default, arguments are passed by value: the method gets a copy, and even if it changes it, the caller's variable stays the same. The ref keyword passes the variable itself, so the method can change it. out is for handing results back: the method must assign a value to an out parameter. Both ref and out are written in the method header and in the call.
int score = 10;
AddBonusCopy(score);
Console.WriteLine($"After copy: {score}");
AddBonus(ref score);
Console.WriteLine($"After ref: {score}");
Divide(17, 5, out int quotient, out int remainder);
Console.WriteLine($"17 / 5 = {quotient}, remainder {remainder}");
if (int.TryParse("42", out int number))
Console.WriteLine($"Parsed: {number}");
if (!int.TryParse("forty", out _))
Console.WriteLine("'forty' is not a number");
void AddBonusCopy(int value) => value += 5;
void AddBonus(ref int value) => value += 5;
void Divide(int x, int y, out int q, out int r)
{
q = x / y;
r = x % y;
}After copy: 10 After ref: 15 17 / 5 = 3, remainder 2 Parsed: 42 'forty' is not a number
AddBonusCopychanged only a copy, soscorestayed 10.- With
ref, the method received the variable itself and made it 15. int.TryParseusesout: if the conversion works it returnstrueand writes the number, otherwise it returnsfalsewithout throwing an error.out _says we do not need the result.
Key points
- A method header has a return type, a name and parameters —
double Area(double w, double h). - A
voidmethod returns nothing; other methods give back a value withreturn. - A one-expression method can be written briefly with
=>. - Default values (
int discount = 0) make an argument optional; named arguments (seats: 3) free you from the order. - Arguments are passed as copies by default;
refpasses the variable itself, andouthands a result back.
Check yourself
10 questions. Every correct answer earns XP.
void mean?