Methods: splitting the program into pieces
When a program grows, keeping everything in a single sequence of lines becomes unmanageable. Methods (also called functions) let you give a name to a piece of code and reuse it as many times as needed. They have three huge advantages: you avoid repeating code, each piece can be tested separately, and the program reads like a list of named actions, such as CalculateTotal or PrintReceipt, instead of a wall of statements.
Anatomy of a method
A method is declared with four parts: the type it returns, the name, the parameters in parentheses and the body in braces. If it returns nothing, the type is void. If it returns something, the body must end every path with the word return followed by a value of that type. By convention, method names are written in PascalCase (each word capitalized) and should be verbs that say what they do. In a program with top-level statements, you can write the methods directly in the Program.cs file; they are called local functions and can appear before or after their first use.
Greet("Ana");
Greet("Luis");
int result = Add(4, 5);
Console.WriteLine(result); // 9
Console.WriteLine(Add(Add(1, 2), 3)); // 6
Console.WriteLine(IsAdult(20)); // True
Console.WriteLine(Square(1.5)); // 2.25
void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
int Add(int a, int b)
{
return a + b;
}
bool IsAdult(int age) => age >= 18; // expression-bodied method
double Square(double x) => x * x;Returning values and finishing early
return not only delivers a value: it also ends the method at that very point. This lets you write guard clauses at the beginning, which discard invalid cases and keep the rest of the method clean. If a method declares that it returns an int, the compiler requires every possible path to end in a return; if one is missing, you will see the error "not all code paths return a value". A void method can use a bare return, without a value, to leave early. To return several values at once there is the tuple, for example (int min, int max), which can be deconstructed when received.
(int min, int max) result = MinMax([7, 3, 9, 1, 5]);
Console.WriteLine($"{result.min} {result.max}"); // 1 9
var (low, high) = MinMax([10, 20]);
Console.WriteLine($"{low} {high}"); // 10 20
Console.WriteLine(Divide(10, 4)); // 2.5
Console.WriteLine(Divide(1, 0)); // 0
(int min, int max) MinMax(int[] values)
{
int min = values[0];
int max = values[0];
foreach (int v in values)
{
if (v < min) min = v;
if (v > max) max = v;
}
return (min, max);
}
double Divide(double a, double b)
{
if (b == 0) return 0; // guard clause
return a / b;
}Overloading and good practices
You can have several methods with the same name if their parameters differ in number or type: this is called overloading. Console.WriteLine is a good example, because it accepts text, numbers and many more. Overloading does not work with local functions, so it is written as static methods inside a class, which in a top-level program is declared after the statements; we will study classes in depth in week 6. The compiler chooses the method according to the arguments you pass. A good practice is for each method to do one thing and fit on the screen; if you need a comment to explain a block inside a long method, that block probably deserves its own method with a clear name.
Console.WriteLine(Shapes.Area(3)); // 9 (square)
Console.WriteLine(Shapes.Area(3, 4)); // 12 (rectangle)
Console.WriteLine(Shapes.Area(1.0)); // 3.14 (circle)
// Types go after the top-level statements
static class Shapes
{
public static int Area(int side) => side * side;
public static int Area(int width, int height) => width * height;
public static string Area(double radius) => (Math.PI * radius * radius).ToString("0.00");
}检验所学
第 1 / 2Which return type do you use if the method returns nothing?
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符